Check For Special Characters in JavaScript
Sometimes situation arises when you want to check for special characters in a string. But in JavaScript there is no direct methods that can check for Special Characters. To achieve this will have to use the JavaScript programming to develop an code that will perform the job of checking for special characters. The main part that perform this operation are the for loop construct and the indexOf method in JavaScript.
var iChars = "!@#$%^&*()+=-[]\\\';,./{}|\":<>?~_"; for (var i = 0; i < data.length; i++) { if (iChars.indexOf(data.charAt(i)) != -1) { alert ("Your string has special characters. \nThese are not allowed."); return false; } }
Explanation:
- I have defined the list of all the special characters in iChars variable
- Also data refers to the string data for which you are checking for the special characters
- Here we check the individual vales inside the data variable with the special character list. If the value matches with the special char list then we display an alert messge
Similar Posts
Did you enjoy this post? Why not leave a comment below and continue the conversation, or subscribe to my feed and get articles like this delivered automatically to your feed reader.


good solution keep it up