Remove special characters - jQuery

In this post we will see how to remove special characters like !,@,$,*,^ ...etc. from the string. For that we need to specify the special characters in regular expressions. Then by passing specified regular expression to .replace method in jquery and replace it with '' blank.

remove special characters from string in jquery

Example to remove special characters from string - jquery

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <title>Remove special character fromstring</title>
    <script type="text/javascript">
        $(document).ready(function () {
            $("#Send").click(function () {
                var originalstring = $("#txtinput").val();
                var filteredString = originalstring.toLowerCase().replace( /[\*\^\'\!\@\$]/g , '');
                alert(filteredString);
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:TextBox runat="server" ID="txtinput"></asp:TextBox>
    <asp:Button runat="server" ID="Send" Text="Send" />
    </div>
    </form>
</body>
</html>


We can use regular expressions to define the special character set that we need to remove from string. so if you want to remove * from the string the regular expression will be /[\*]/g. Now if you want to remove ! also the add ! to regular expression like /[\*\!]/g and so on.

0 Comments :

Post a Comment