'IsNullOrWhitespace' in JavaScript?
For a succinct modern cross-browser implementation, just do:
function isNullOrWhitespace( input ) {
return !input || !input.trim();
}
Here's the jsFiddle. Notes below.
The currently accepted answer can be simplified to:
function isNullOrWhitespace( input ) {
return (typeof input === 'undefined' || input == null)
|| input.replace(/\s/g, '').length < 1;
}
And leveraging falsiness, even further to:
function isNullOrWhitespace( input ) {
return !input || input.replace(/\s/g, '').length < 1;
}
trim() is available in all recent browsers, so we can optionally drop the regex:
function isNullOrWhitespace( input ) {
return !input || input.trim().length < 1;
}
And add a little more falsiness to the mix, yielding the final (simplified) version:
function isNullOrWhitespace( input ) {
return !input || !input.trim();
}
no, but you could write one
function isNullOrWhitespace( str )
{
// Does the string not contain at least 1 non-whitespace character?
return !/\S/.test( str );
}
It's easy enough to roll your own:
function isNullOrWhitespace( input ) {
if (typeof input === 'undefined' || input == null) return true;
return input.replace(/\s/g, '').length < 1;
}