[Javascript] How to check for special characters present in a string?


I want to check if there are any special characters present in a given string and return true if exists. How to check that in Javascript?

1 Answer

3 years ago by

You can use a regex to test if a string contains a special character or not. For example, using Regex test() function returns true if special characters present else returns false.

let specialChars =/[`!@#$%^&*()_\-+=\[\]{};':"\\|,.<>\/?~ ]/;

console.log(specialChars.test("String with speci@l ch@ract&r$"));
console.log(specialChars.test("String with spaces"));
console.log(specialChars.test("StringWithoutSpaces"));

Run here https://onecompiler.com/javascript/3xnpa8v9c

3 years ago by Meera