157

I need to check to see if a variable is null or has all empty spaces or is just blank ("").

I have the following, but it is not working:

var addr;
addr = "  ";

if (!addr) {
    // pull error 
}

If I do the following, it works:

if (addr) {

}​

What I need is something like the C# method String.IsNullOrWhiteSpace(value).

Jon Schneider
  • 25,758
  • 23
  • 142
  • 170
Nate Pet
  • 44,246
  • 124
  • 269
  • 414

16 Answers16

206

A non-jQuery solution that more closely mimics IsNullOrWhiteSpace, but to detect null, empty or all-spaces only:

function isEmptyOrSpaces(str){
    return str === null || str.match(/^ *$/) !== null;
}

...then:

var addr = '  ';

if(isEmptyOrSpaces(addr)){
    // error 
}

* EDIT * Please note that op specifically states:

I need to check to see if a var is null or has any empty spaces or for that matter just blank.

So while yes, "white space" encompasses more than null, spaces or blank my answer is intended to answer op's specific question. This is important because op may NOT want to catch things like tabs, for example.

Madbreaks
  • 19,094
  • 7
  • 58
  • 72
  • 91
    Whitespace can also include tabs, other kinds of spaces, etc. Use `/^\s*$/` to catch those, too. – grant Aug 09 '13 at 00:26
  • 4
    @Grant I purposefully did NOT do that because op said _"I need to check to see if a var is null or has any empty spaces or for that matter just blank"_. – Madbreaks Sep 25 '13 at 18:56
  • 6
    What about using test() instead of match()? return str === null || (/^ *$/).test(str); – Mario Levrero Sep 24 '14 at 09:43
  • @subsci Grant's suggestion would return a false-positive for a string containing tabs. Are you suggesting I change the name of the function? Ok. – Madbreaks Sep 24 '14 at 18:56
  • 1
    @MarioLevrero I like it! `test` is also faster as I recall. – Madbreaks Sep 24 '14 at 18:57
  • 1
    @Madbreaks I simply meant that Grant's suggestion works and has the semantics of the C# function. You can try this and variants: `function isNullOrWhiteSpace(str){ return str === null || str.match(/^\s*$/) !== null; } var addr = '\t\t'; if (isNullOrWhiteSpace(addr)) { alert('yes'); } else { alert ('no'); } addr = '\thello\t'; if (isNullOrWhiteSpace(addr)) { alert('yes'); } else { alert ('no'); }` – subsci Sep 26 '14 at 02:58
  • @subsci Grant's suggestion doesn't work, because it will match tabs which the op did *not* want. – Madbreaks Sep 26 '14 at 15:41
  • 13
    @Madbreaks the op stated "What I need is something like this C# method: String.IsNullOrWhiteSpace". That method treats tabs as whitespace. – subsci Sep 26 '14 at 22:09
  • @subsci You need to read the rest of the question: *"so that if it is null or has any spaces or no space, I can trap it"*. "Something like" != "something identical to", and in this case it's the op's last sentence which describes *exactly* what he wanted. – Madbreaks Sep 26 '14 at 22:27
  • @Madbreaks you're absolutely right, I don't know **exactly** what he wanted ;) – subsci Sep 26 '14 at 23:01
  • 1
    It think you'll find Empty Spaces on The Wall, but not in user input. This is cause for confusion here. I think the OP could have meant _just spaces_ or just _white spaces_, the latter including tabs as well. – R. Schreurs Apr 24 '23 at 15:26
61
if (addr == null || addr.trim() === ''){
  //...
}

A null comparison will also catch undefined. If you want false to pass too, use !addr. For backwards browser compatibility swap addr.trim() for $.trim(addr).

Ricardo Tomasi
  • 34,573
  • 2
  • 55
  • 66
  • 1
    _"If you want false to pass too, use !addr"_ - breaks down if `addr` is zero. – Madbreaks Apr 05 '17 at 17:10
  • 2
    why is the first one `==` and second matching `===`? – Max Sep 09 '20 at 07:11
  • 2
    Using "addr == null" will also match undefined. If you used "addr === null" it would only match null. Using the === for the second match forces a match only on empty string. – Ed Downs Sep 25 '20 at 16:16
  • @EdDowns aaaand that's why we should always use strict comparison. If a check for `undefined` is required, do so explicitly. This makes the code easier to understand and to support. – Madbreaks Nov 22 '21 at 20:05
22

You can use if(addr && (addr = $.trim(addr)))

This has the advantage of actually removing any outer whitespace from addr instead of just ignoring it when performing the check.

Reference: http://api.jquery.com/jQuery.trim/

ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
18

Old question, but I think it deservers a simpler answer.

You can simply do:

var addr = "  ";

if (addr && addr.trim()) {

    console.log("I'm not null, nor undefined, nor empty string, nor string composed of whitespace only.");

}
sandre89
  • 5,218
  • 2
  • 43
  • 64
  • 1
    Shouldn't it be `addr && addr.trim()`? With a single `&` it didn't work for me but it does with `&&`. – markv12 Jun 30 '20 at 03:21
7

Simplified version of the above: (from here: https://stackoverflow.com/a/32800728/47226)

function isNullOrWhitespace( input ) {
  return !input || !input.trim();
}
Aaron Hoffman
  • 6,604
  • 8
  • 56
  • 61
5

You can create your own method Equivalent to

String.IsNullOrWhiteSpace(value)

function IsNullOrWhiteSpace( value) {

    if (value== null) return true;

    return value.replace(/\s/g, '').length == 0;
}
Shehzad
  • 2,870
  • 17
  • 21
4

When checking for white space the c# method uses the Unicode standard. White space includes spaces, tabs, carriage returns and many other non-printing character codes. So you are better of using:

function isNullOrWhiteSpace(str){
    return str == null || str.replace(/\s/g, '').length < 1;
}
Joao Leme
  • 9,598
  • 3
  • 33
  • 47
  • Op explicitly states the goal is to check for *spaces*, not whitespace. – Madbreaks Jul 10 '13 at 23:12
  • 7
    Op says "What I need is something like this C# method: String.IsNullOrWhiteSpace(value)". And if you r just checking for spaces don't name your function isNullOrWhiteSpace but instead name it IsNullOrEmtpy. – Joao Leme Jul 11 '13 at 13:17
  • The C# method *would work* to check to see if a string was null or a series of spaces. Op wanted something "like" that, but to check specifically for spaces. – Madbreaks Jul 11 '13 at 23:13
4
isEmptyOrSpaces(str){
    return !str || str.trim() === '';
}
Ali
  • 125
  • 2
  • 4
  • 4
    Is there any need to duplicate existing answers? Or have you changed anything to the prior answers that makes a relevant difference? – Nico Haase May 17 '19 at 15:37
3

Maybe it's the easiest way

if (!addr?.trim()){
  //error
}
Parsa S
  • 145
  • 5
1

I use simply this and this works for me most of the time. it first trim the white spaces and then checks the length.

 if(value.trim().length === 0)
{
   //code for empty value
}
KUSH
  • 33
  • 5
1

I usually do this:

!value?.toString().trim()

Which you can wrap in a function if you want

function isNullOrWhiteSpace(value) {
  return !value?.toString().trim()
}

console.log(isNullOrWhiteSpace(''))
console.log(isNullOrWhiteSpace(' '))
console.log(isNullOrWhiteSpace(undefined))
console.log(isNullOrWhiteSpace(null))
console.log(isNullOrWhiteSpace('0'))
console.log(isNullOrWhiteSpace(0))

Easily adaptable if you wish to check only against strings

if (typeof(value) === 'number') throw new Error('Invalid input')
0

Try this out

/**
  * 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');
0
isEmptyOrSpaces(str){
    return str === null || str.trim().length>0;
}
Tiago Martins Peres
  • 14,289
  • 18
  • 86
  • 145
0
function isEmptyOrSpaces(str){
    return str === null || str.match(/^[\s\n\r]*$/) !== null;
}
pico
  • 1,660
  • 4
  • 22
  • 52
0

Based on Madbreaks' answer, and I wanted to account for undefined as well:

function isNullOrWhitespace(str) {
  return str == null || str.match(/^\s*$/) !== null;
}

Jest tests:

it('works for undefined', () => {
    expect(isNullOrWhitespace(undefined)).toEqual(true);
});

it('works for null', () => {
    expect(isNullOrWhitespace(null)).toEqual(true);
});

it('works for empty', () => {
    expect(isNullOrWhitespace('')).toEqual(true);
});

it('works for whitespace', () => {
    expect(isNullOrWhitespace(' ')).toEqual(true);
    
    // Tab
    expect(isNullOrWhitespace(' ')).toEqual(true);
});
datchung
  • 3,778
  • 1
  • 28
  • 29
-2

You can try this:

do {
   var op = prompt("please input operatot \n you most select one of * - / *  ")
} while (typeof op == "object" || op == ""); 
// execute block of code when click on cancle or ok whthout input
Dino
  • 7,779
  • 12
  • 46
  • 85