How to know whether string contains special characters or not in JavaScript

In this section I will show you that how we can use the simple regular expression to know whether the specified string contains the special characters or not.

We have discussed several tasks in the JavaScript using the regular expression (Use of regular expression in javascript).
In the following example I am using the .test() JavaScript method.

The [regx string].test(val) returns the true and false value: these values indicates whether or not a pattern exists in a searched string. You can also use the following code to disallow the all special characters in the input control using the JavaScript.

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title></title>
  <script type="text/javascript"
     src="http://code.jquery.com/jquery-1.7.js"></script>
  <script type="text/javascript">
      $(function () {
        $('#btnOk').click(function () {
          var str = $('#txtName').val();
	  var pattern=/^[a-zA-Z0-9- ]*$/;
          if (pattern.test(str) == false) {
            alert('Name does not contain illegal characters.');
          }
         })
        })
    </script>
</head>
<body>
    <form id="form1">
        <div>
            Enter your name:<input type="text" id="txtName" />
            <input type="button" id="btnOk" value="Ok" />
        </div>
    </form>
</body>
</html>

from the above example if user will put any special character(s) in the input control, than click event of the button ‘btnOk’ display a alert message.

Author: Hirendra Sisodiya

Programmer at PSPL. Can be found on Google Plus.