Regular Expression to Replace Special Characters from String using JavaScript

Regular Expression to Replace Special Characters from String using JavaScript

Hello everyone, I am going share the code sample for how to Replace Special Charactersfrom String  like you can see the below image.



In the above output image, you can see, when I clicked on "Remove Special Characters" button to display an alert text-box input text are not showing the special characters in the result string but I putting the some special charters in the in the text-box, you can see, edit and click on below given plunker link.


The JavaScript code with regular expression for Replacing Special Characters from String  as give below

function removeSpecialCharacters() {
    var regExpr = /[^a-zA-Z0-9-. ]/g;
    var userText = document.getElementById('user').value;
    alert(userText.replace(regExpr, ""));
}

The Full Live demo code as given below

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>JavaScript Regular Expression to Replace Special Characters from String</title>
    <link rel="stylesheet" href="style.css" />
    <script data-require="jquery" data-semver="2.1.4" src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
    <script type="text/javascript">
        function removeSpecialCharacters() {
            var regExpr = /[^a-zA-Z0-9-. ]/g;
            var userText = document.getElementById('user').value;
            alert(userText.replace(regExpr, ""));
        }
    </script>
</head>
<body>
    <div>
        <h1>JavaScript Regular Expression to Replace Escape Special Characters from String</h1>
    </div>
    <div>
        <h2>Enter Your Input Text</h2>
    </div>
    <div>
        <input type="text" id="user" value="Hello Anil' Welcome you  to#$% code-@!sample.$*^com" class="text" />
        <input type="button" id="btnRemove" value="Remove Special Characters" onclick="removeSpecialCharacters()" class="success" />
    </div>
</body>
</html>

The CSS code for Textbox and button as given below

<style>
    h1 {
        color: Green;
    }

    .success {
        background-color: #57A957;
        color: white;
        background-repeat: no-repeat;
        display: inline-block;
        height: 40px;
        vertical-align: middle;
    }

    .text {
        height: 36px;
        position: relative;
        border: 1px solid #cdcdcd;
        font-size: 14px;
        width: 300px;
    }
</style>


The output : go to link http://embed.plnkr.co/06dJ3A/preview

Thank you!




ANIL SINGH

Anil Singh is an author, tech blogger, and software programmer. Book writing, tech blogging is something do extra and Anil love doing it. For more detail, kindly refer to this link..
My Blogs - https://code-sample.com and https://code-sample.xyz
My Book1 - BEST SELLING ANGULAR BOOK (INCLUDING ALL VERSIONS 2, 4, 5, 6, 7)
My Book2 - ANGULAR 2 INTERVIEW QUESTIONS BOOK - Both Books are Available on WorldWide.

www.code-sample.com/. Powered by Blogger.