One can check if the string does not contain any non-whitespace characters with a regular expression. This method will only check each character at most once and will exit early as soon as it encounters a character that is not whitespace.
if(!/\S/.test(str)){
console.log('str contains only whitespace');
}
One could also use String#trim to remove all whitespace from the beginning and end of the string. If the string only contained whitespace, the result will be an empty string, which is falsy.
if(!str.trim()){
console.log('str contains only whitespace');
}
If the string might be null or undefined, the optional chaining operator can be used.
if(!str?.trim()){
console.log('str is null or undefined, or contains only whitespace');
}
javascript match string.