What is the best way to check if a string contains only whitespace?
The string is allowed to contain characters combined with whitespace, but not just whitespace.
What is the best way to check if a string contains only whitespace?
The string is allowed to contain characters combined with whitespace, but not just whitespace.
Instead of checking the entire string to see if there's only whitespace, just check to see if there's at least one character of non whitespace:
if (/\S/.test(myString)) {
// string is not empty and not just whitespace
}
if (/^\s+$/.test(myString))
{
//string contains only whitespace
}
this checks for 1 or more whitespace characters, if you it to also match an empty string then replace + with *.
Just check the string against this regex:
if(mystring.match(/^\s+$/) === null) {
alert("String is good");
} else {
alert("String contains only whitespace");
}
I've used the following method to detect if a string contains only whitespace. It also matches empty strings.
if (/^\s*$/.test(myStr)) {
// the string contains only whitespace
}