Use the test() method to check if a string contains whitespace, e.g. /\s/. test(str) . The test method will return true if the string contains at least one whitespace character and false otherwise.
Space, tab, line feed (newline), carriage return, form feed, and vertical tab characters are called "white-space characters" because they serve the same purpose as the spaces between words and lines on a printed page — they make reading easier.
This question is tagged with jQuery. In jQuery, you can run the following:
if ( $.trim( $('#myInput').val() ) == '' )
alert('input is blank');
/^\s+$/.test(userText)
Change the +
to *
to include the empty string ''
as a positive match.
Edit
More often than not though you need to trim whitespace from user-entered text and simply test if it's non-empty:
userText = userText.replace(/^\s+/, '').replace(/\s+$/, '');
if (userText === '') {
// text was all whitespace
} else {
// text has real content, now free of leading/trailing whitespace
}
This will also work:
var text = " ";
text.trim().length == 0; //true
Like this...
function isEmpty(str) {
return str.replace(/^\s+|\s+$/g, '').length == 0;
}
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