admin管理员组

文章数量:1129016

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).

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).

Share Improve this question edited Nov 15, 2018 at 15:29 Jon Schneider 27k24 gold badges151 silver badges180 bronze badges asked Apr 19, 2012 at 16:17 Nate PetNate Pet 46.2k127 gold badges274 silver badges419 bronze badges 3
  • 5 Do you really mean has *any* empty spaces? Or do you mean is all empty spaces? – Madbreaks Commented Apr 19, 2012 at 16:54
  • 1 what about undefined? – CodeToad Commented Jan 5, 2015 at 9:32
  • Possible duplicate of How do you check for an empty string in JavaScript? – T.Todua Commented Dec 4, 2018 at 9:29
Add a comment  | 

17 Answers 17

Reset to default 216

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.

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).

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/

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.");

}

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

function isNullOrWhitespace( input ) {
  return !input || !input.trim();
}

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

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;
}
isEmptyOrSpaces(str){
    return !str || str.trim() === '';
}

Maybe it's the easiest way

if (!addr?.trim()){
  //error
}

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

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
}

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');
isEmptyOrSpaces(str){
    return str === null || str.trim().length>0;
}
function isEmptyOrSpaces(str){
    return str === null || str.match(/^[\s\n\r]*$/) !== null;
}

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

I based the following snippet on MadBreak's answer. In my case, there were some scenarios where a non-string object was passed in, which threw an exception. The following function checks for the existence of the str.match function before calling it.

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

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

本文标签: jqueryHow to check if a variable is null or empty string or all whitespace in JavaScriptStack Overflow