What is the easiest way to check in Javascript whether the input text field is empty (contains nothing or white spaces only)?
To check if a string contains only spaces, call the trim() method on the string and check if the length of the result is equal to 0 . If the string has a length of 0 after calling the trim method, then the string contains only spaces.
/^\s+$/ is checking whether the string is ALL whitespace: ^ matches the start of the string. \s+ means at least 1, possibly more, spaces. $ matches the end of the string.
Both methods are used to check for blank or empty strings in java. The difference between both methods is that isEmpty() method returns true if, and only if, string length is 0. isBlank() method only checks for non-whitespace characters. It does not check the string length.
You can do this by simply using trim. var str = " "; if (str. trim(). length == 0) { console.
var str = document.getElementById("myInput").value;
if (str.match(/^\s*$/)) {
// nothing, or nothing but whitespace
} else {
// something
}
You are looking for something like trim function, right?
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