In this blog post you’ll learn how to check for a string contains a special characters or not using JavaScript. Learn efficient ways to check for special characters in a string.
Way 1: Match Method With Regular Expression For Matching the Special Characters.
We’ll match for these special characters (!@#%^&*()_\|/?]/) in a given string. You can also use search() method.
JavaScript
let string = "Hello & welcome to maketechstuff.com";
console.log("string: ", string);
if (string.match(/[!@#%^&*()_\|/?]/)) {
console.log("Output: ", "No special characters are allowed in a string");
} else {
console.log("Output: ", "No problem");
}
Output:
With special characters. (&).
In the above way I've added this special characters (!@#%^&*()_\|/?]/) check or match for it in a string. But you can also takes a different approach that allows only letters(a to z), dot(.), numbers and white spaces in a string.
Way 2: Match Method With Regular Expression For Matching the Characters Other than (a-Z),(0-9),(.) and Spaces.
We’ll show the error If any characters are present in a string other than the alphabet (small and capital), dot (.), numbers and white spaces.
JavaScript
let string = "Hello & welcome to maketechstuff.com";
console.log("string: ", string);
if (string.match(/[^(.)\sA-Za-z0-9]/)) {
console.log("Output: ", "Only letters (a to z), numbers, white spaces and dot(.) are allowed");
} else {
console.log("Output: ", "No problem");
}
Output:
With special characters (&).
You also use search() method:
JavaScript
let string = "hello welcome to maketechstuff.com";
console.log("string: ", string);
// Search method return -1 if no match found. And if match found, it returns the index value of the search value.
let i = string.search(/[^\.\sa-zA-Z0-9]/);
console.log("Search Method returns: ", i);
if (i == -1) {
console.log("Output: ", "No problem");
} else {
console.log("Output: ", "Only letters (a to z), numbers, white spaces and dot(.) are allowed");
}
// Output:
// string: hello welcome to maketechstuff.com
// Search Method returns: -1
// Output: No problem
So that's how you can check for special characters in a string using javascript. If you have any query or suggestion feel free to write in the comment section.
You may like:
- How to detect the numeric values present in a string using JavaScript.
- How to extract the numbers present in a string using JavaScript.
- How to remove the numeric values from a string using JavaScript.
Share your thoughts.