How to check whether string contains special characters or not using JavaScript

Here I am going to show you How to check whether string contains special characters or not using JavaScript. Some time you need to validate form input value before submitting and prevent string from special character. You can simply use javascript test() function to validate string for special character and The [regx string].test(str) returns the true and false value, these values indicates whether pattern exists in string or not.



The following JavaScript example validate string only for alphanumeric values.

if(/^[a-zA-Z0-9]*$/.test(str) == false){
    
}

You can also allow other characters as per your requirement. The following JavaScript code accepts letters (a-z and A-Z), numbers (0-9), spaces, hyphen(-), comma(,), and underscore(_) characters.

if(/^[a-zA-Z0-9- ,_]*$/.test(str) == false){
    
}