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
}
Simplest answer if your browser supports the trim()
function
if (myString && !myString.trim()) {
//First condition to check if string is not empty
//Second condition checks if string contains 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 *
.
Well, if you are using jQuery, it's simpler.
if ($.trim(val).length === 0){
// string is invalid
}
Just check the string against this regex:
if(mystring.match(/^\s+$/) === null) {
alert("String is good");
} else {
alert("String contains only whitespace");
}
if (!myString.replace(/^\s+|\s+$/g,""))
alert('string is only whitespace');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With