Improve your skills

August 29, 2016

Remove Special Characters From String Using Regular Expression (Regex) in JavaScript


In this article, we discuss about how to remove special characters (like !, #, $, %,  >, ?, :, #,@ etc.) from string in jQuery/JavaScript using Regular Expression (Regex). 

First, we take a input text or textarea and a input button in body as show in below-

HTML:
<body style="background: #E0EDFA; text-align: center; margin-top: 250px;">
<form id="form1">
<h1>Remove Special Characters From String Using Regular Expression (Regex) in JavaScript</h1>
<textarea id="txtString" rows="5" cols="50" placeholder=" write your text here"></textarea><br />
<input id="btnRemoveSpecialCharacter" type="button" value="Remove Special Characters" onclick="getSpeCharFreeText();" />
</form>
</body>

After that, attach the jquery library link and write the below javascript code in head part as shown below-

JS:
<head>
<script src="https://code.jquery.com/jquery-3.1.0.min.js" type="text/javascript"></script>
    <script type="text/javascript">

        function getSpeCharFreeText(id) {
            var txtString = $('#txtString').val().trim();
            var regExpr = /[^a-zA-Z0-9-. ]/g;
            var str = txtString.replace(regExpr, '')
            $('#txtString').val(str);
        }

    </script>
</head>

Now save the file and run on browser.

After write string (containing special characters) in textarea, click on 'Remove Special Characters' button. Then all the special characters(!, #, $, %,  >, ?, :, #,@ etc.) are removed and simple text content visible on the textarea.

Result:
Remove Special Characters From String Using Regular Expression (Regex) in JavaScript










Live Demo:



0 comments:

Post a Comment

Subscribe for Latest Update

Popular Posts