'IsNullOrWhitespace' in JavaScript?

Javascript.NetStringIs EmptyIsnullorempty

Javascript Problem Overview


Is there a JavaScript equivalent to .NET's String.IsNullOrWhitespace so that I can check if a textbox on the client-side has any visible text in it?

I'd rather do this on the client-side first than post back the textbox value and rely only on server-side validation, even though I will do that as well.

Javascript Solutions


Solution 1 - 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();
}

Solution 2 - Javascript

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;
}

Solution 3 - Javascript

no, but you could write one

function isNullOrWhitespace( str )
{
  // Does the string not contain at least 1 non-whitespace character?
  return !/\S/.test( str );
}

Solution 4 - Javascript

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');

Solution 5 - Javascript

You can use the regex /\S/ to test if a field is whitespace, and combine that with a null check.

Ex:

if(textBoxVal === null || textBoxVal.match(/\S/)){
    // field is invalid (empty or spaces)
}

Solution 6 - Javascript

trim() is a useful string-function that JS is missing..

Add it:

String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g,"") }

Then: if (document.form.field.value.trim() == "")

Solution 7 - Javascript

You must write your own:

function isNullOrWhitespace(strToCheck) {
    var whitespaceChars = "\s";
    return (strToCheck === null || whitespaceChars.indexOf(strToCheck) != -1);
}

Solution 8 - Javascript

Pulling the relevant parts of the two best answers, you get something like this:

function IsNullOrWhitespace(input) {
    if (typeof input === 'undefined' || input == null) return true;
    return !/\S/.test(input); // Does it fail to find a non-whitespace character?
}

The rest of this answer is only for those interested in the performance differences between this answer and Dexter's answer. Both will produce the same results, but this code is slightly faster.

On my computer, using a QUnit test over the following code:

var count = 100000;
var start = performance.now();
var str = "This is a test string.";
for (var i = 0; i < count; ++i) {
    IsNullOrWhitespace(null);
    IsNullOrWhitespace(str);
}
var end = performance.now();
var elapsed = end - start;
assert.ok(true, "" + count + " runs of IsNullOrWhitespace() took: " + elapsed + " milliseconds.");

The results were:

  • RegExp.replace method = 33 - 37 milliseconds
  • RegExp.test method = 11 - 14 milliseconds

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionScottView Question on Stackoverflow
Solution 1 - Javascriptuser4942583View Answer on Stackoverflow
Solution 2 - JavascriptDexterView Answer on Stackoverflow
Solution 3 - JavascriptPeter BaileyView Answer on Stackoverflow
Solution 4 - JavascriptRod lauro RomarateView Answer on Stackoverflow
Solution 5 - JavascriptMcStretchView Answer on Stackoverflow
Solution 6 - JavascriptT4NK3RView Answer on Stackoverflow
Solution 7 - JavascriptlukastymoView Answer on Stackoverflow
Solution 8 - JavascriptJohn FisherView Answer on Stackoverflow