'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();
}
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;
}
no, but you could write one
function isNullOrWhitespace( str )
{
// Does the string not contain at least 1 non-whitespace character?
return !/\S/.test( str );
}
Try this out
Checks the string if undefined, null, not typeof string, empty or space(s
/**
* Checks the string if undefined, null, not typeof string, empty or space(s)
* @param {any} str string to be evaluated
* @returns {boolean} the evaluated result
*/
function isStringNullOrWhiteSpace(str) {
return str === undefined || str === null
|| typeof str !== 'string'
|| str.match(/^ *$/) !== null;
}
You can use it like this
isStringNullOrWhiteSpace('Your String');