Thursday, 6 April 2017

Replace special characters from string using JavaScript Regular Expression

In this post, I will explain how to remove special character from any string using JavaScript Regular Expression? 

To replace special characters from the string we have to use javascript replace function and regular expression like "/[^a-zA-Z0-9 ]/g". In this expression "^" symbol will leave given characters and replace other characters.


<html  lang="">
<head>
    <title>Replace special characters from string using Javascript Regular Expression</title>
    <script type="text/javascript">

        function ReplaceSpecialCharacter() {

            var str = document.getElementById('txtChar').value;
            // It will replace all special characters(Except Aplphabets, Space & Numbers)
            document.getElementById('spnResult').innerHTML = str.replace(/[^a-zA-Z0-9 ]/g, "") 
        }
    </script>

</head>
<body>
    <form style="vertical-align:middle;text-align:center;">
        <div style="width:500px;">
            Enter Text :<input type="text" id="txtChar" value="" />
            <input type="button" id="btn" value="Replace" onclick="ReplaceSpecialCharacter()" />
           <h1><span id="spnResult"></span></h1>
        </div>
    </form>
</body>
</html>

0 comments:

Post a Comment

Please do not enter any spam link in the message box.