'IsNullOrWhitespace' in JavaScript?
Asked Answered
I

8

76

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.

Imperfective answered 5/4, 2011 at 22:41 Comment(3)
You don't need a dedicated function for that. Just test this expression: x.value.trim() === '' (where x is a reference to your input element). This expression will return true if the value is only whitespace, false otherwise. Using a dedicated function for such a simple task is overkill. (Note: you would need to implement trim() for IE8 and below. This is an easy task and something that you would want to do anyway.)Pyxis
well a textbox value can not be null so that is just a waste of a check.Martines
"well a textbox value can not be null." That may be true, but a million other strings can. I have a custom knockout binding on a datepicker, and it can be null.Fragmentation
I
90

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;
}
Intermeddle answered 5/4, 2011 at 22:46 Comment(10)
g = global, i = case insensitive. Actually probably don't need the i. By default javascript replace only replaces the first match, but with the g it replaces all instances.Intermeddle
Does not work with undefined. plnkr.co/edit/oHy8iVk7qio12Klpoh72?p=previewFragmentation
Updated to support undefined. Your other test case is failing before it enter this method @Rhyous.Intermeddle
Dexter, I've given up on "undeclared". Also, I found another site that shows !input works for both (typeof input === 'undefined' || input == null). It works in my tests. Thanks by the way! Sometimes in short comments mentioning a problem, we forget to mention how much the answer helped. Your answer got me started.Fragmentation
Your solution is very good maybe you can add this if (!input) return true; in the condition to make the code simpler @IntermeddleSelfservice
@CarlosEduardoCordón, this doesn't quite do the same thing as the code above - !input will return true for values like the string "false", as an example. Have a look here for more examples: developer.mozilla.org/en-US/docs/Glossary/FalsyIntermeddle
@Intermeddle the code works very well with the change here is an exampleSelfservice
Why use Regex instead of trim()?Seismograph
This was posted in 2011, before trim() was part of the spec - but yes, you could use trim() now! (developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…)Intermeddle
It's funny how an 'easy enough' solution unnecessarily doubles memory requirements.Unthinkable
K
94

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();
}
Klink answered 26/9, 2015 at 18:44 Comment(1)
This may fail with Uncaught TypeError: input.trim is not a function if input isn't a string.Costmary
I
90

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;
}
Intermeddle answered 5/4, 2011 at 22:46 Comment(10)
g = global, i = case insensitive. Actually probably don't need the i. By default javascript replace only replaces the first match, but with the g it replaces all instances.Intermeddle
Does not work with undefined. plnkr.co/edit/oHy8iVk7qio12Klpoh72?p=previewFragmentation
Updated to support undefined. Your other test case is failing before it enter this method @Rhyous.Intermeddle
Dexter, I've given up on "undeclared". Also, I found another site that shows !input works for both (typeof input === 'undefined' || input == null). It works in my tests. Thanks by the way! Sometimes in short comments mentioning a problem, we forget to mention how much the answer helped. Your answer got me started.Fragmentation
Your solution is very good maybe you can add this if (!input) return true; in the condition to make the code simpler @IntermeddleSelfservice
@CarlosEduardoCordón, this doesn't quite do the same thing as the code above - !input will return true for values like the string "false", as an example. Have a look here for more examples: developer.mozilla.org/en-US/docs/Glossary/FalsyIntermeddle
@Intermeddle the code works very well with the change here is an exampleSelfservice
Why use Regex instead of trim()?Seismograph
This was posted in 2011, before trim() was part of the spec - but yes, you could use trim() now! (developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…)Intermeddle
It's funny how an 'easy enough' solution unnecessarily doubles memory requirements.Unthinkable
H
3

no, but you could write one

function isNullOrWhitespace( str )
{
  // Does the string not contain at least 1 non-whitespace character?
  return !/\S/.test( str );
}
Henig answered 5/4, 2011 at 22:48 Comment(6)
should be !/\S/.test(typeof(str) == 'string' ? str : ''). If it's not, null, undefined, any any object will return true.Andrade
I would write it as !str || !/\S/.test(str);Kosiur
@cwolves what browser do you use where HTMLInputElement.value ever returns null? Just because the question asker thinks "null" is a possible value doesn't mean it actually is.Henig
none, but you're writing a generic function that may be used in another context :)Andrade
@cwolves I guess we just interpreted the "null" in the function name differently. I took it to be "null string", not the actual null value. en.wikipedia.org/wiki/Empty_stringHenig
This fails for both null and undefined values: plnkr.co/edit/zWruFu?p=previewFragmentation
G
3

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');
Goltz answered 22/11, 2018 at 8:15 Comment(0)
E
0

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)
}
Estus answered 5/4, 2011 at 22:46 Comment(2)
This doesn't check for null valuesTeresiateresina
if textBoxVal is null, then the first part of your condition will throw. You need the textBoxVal === null first.Curvaceous
F
0

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() == "")

Florencio answered 5/4, 2011 at 22:49 Comment(1)
String.prototype.trim is part of JavaScript since v5.1 / June 2011Youngster
U
0

You must write your own:

function isNullOrWhitespace(strToCheck) {
    var whitespaceChars = "\s";
    return (strToCheck === null || whitespaceChars.indexOf(strToCheck) != -1);
}
Unprovided answered 5/4, 2011 at 22:50 Comment(1)
This technique only works for blank strings such as "" and not for strings with multiple whitespace characters.Ageold
M
0

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
Massage answered 11/6, 2015 at 22:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.