1. 程式人生 > >如何檢查JavaScript中的空字串?

如何檢查JavaScript中的空字串?

英文原文地址為:How do you check for an empty string in JavaScript?

I saw this thread, but I didn't see a JavaScript specific example. Is there a simple string.Empty available in JavaScript, or is it just a case of checking for ""?

我看到了這個執行緒,但是我沒有看到一個JavaScript特定的例子。有一個簡單的字串。在JavaScript中是空的,還是隻需要檢查一下?

30 個解決方案

#1

2613  

If you just want to check whether there's any value, you can do

如果你想檢查是否有任何值,你可以。

if (strValue) {
    //do something
}

If you need to check specifically for an empty string over null, I would think checking against "" is your best bet, using the === operator (so that you know that it is, in fact, a string you're comparing against).

如果您需要專門檢查空字串,那麼我認為檢查“”是您最好的選擇,使用===操作符(這樣您就知道它實際上是一個您正在比較的字串)。

#2

867  

For checking if a string is empty, null or undefined I use:

用於檢查字串是否為空、null或未定義的I:

function isEmpty(str) {
    return (!str || 0 === str.length);
}

For checking if a string is blank, null or undefined I use:

用於檢查字串是否為空、空或未定義的I使用:

function isBlank(str) {
    return (!str || /^\s*$/.test(str));
}

For checking if a string is blank or contains only white-space:

用於檢查字串是否為空或僅包含空白:

String.prototype.isEmpty = function() {
    return (this.length === 0 || !this.trim());
};

#3

212  

All the above are good but this will be even better. use !!(not not) operator.

以上這些都很好,但這將會更好。使用! !(不)運算元。

if(!!str){
some code here;
}

or use type casting:

或者使用型別鑄造:

if(Boolean(str)){
    codes here;
}

Both do the same function, type cast the variable to boolean, where str is a variable.
Returns false for null,undefined,0,000,"",false.
Returns true for string "0" and whitespace " ".

兩者都執行相同的功能,型別將變數轉換為boolean,其中str是一個變數。0000年為空返回false,未定義的,“”,假的。返回true,字串“0”和空格“”。

#4

84  

If you need to make sure that the string is not just a bunch of empty spaces (I'm assuming this is for form validation) you need to do a replace on the spaces.

如果您需要確保字串不只是一堆空空間(我假設這是表單驗證),那麼您需要在空格上做一個替換。

if(str.replace(/\s/g,"") == ""){
}

#5

74  

The closest thing you can get to str.Empty (with the precondition that str is a String) is:

您可以訪問的最接近的東西是:empty(具有str為字串的前提條件)為:

if (!str.length) { ...

#6

40  

I use :

我使用:

function empty(e) {
  switch (e) {
    case "":
    case 0:
    case "0":
    case null:
    case false:
    case typeof this == "undefined":
      return true;
    default:
      return false;
  }
}

empty(null) // true
empty(0) // true
empty(7) // false
empty("") // true
empty((function() {
    return ""
  })) // false

#7

24  

var s; // undefined
var s = ""; // ""
s.length // 0

There's nothing representing an empty string in JavaScript. Do a check against either length (if you know that the var will always be a string) or against ""

JavaScript中沒有表示空字串的東西。對任意長度進行檢查(如果您知道var始終是字串)或“”

#8

22  

I would not worry too much about the most efficient method. Use what is most clear to your intention. For me that's usually strVar == "".

我不會太擔心最有效的方法。使用最清晰的意圖。對我來說,通常是strVar == "

EDIT: per comment from Constantin, if strVar could some how end up containing an integer 0 value, then that would indeed be one of those intention-clarifying situations.

編輯:來自Constantin的評論,如果strVar可能有一些最終包含一個整數0值,那麼這將確實是一種意圖澄清的情況。

#9

21  

Try:

試一試:

if (str && str.trim().length) {  
    //...
}

#10

18  

Function:

功能:

function Is_Empty_or_Undefined (MyVar){      return (

        (typeof MyVar== 'undefined')        //undefined
                    ||
        (MyVar == null)                     //null
                    ||
        (MyVar == false)  //!MyVariable     //false
                    ||
        (MyVar.length == 0)                 //empty
                    ||
        (MyVar == "")                       //empty
                    ||
        (MyVar.replace(/\s/g,"") == "")     //empty
                    ||
        (!/[^\s]/.test(MyVar))              //empty
                    ||
        (/^\s*$/.test(MyVar))                //empty
  );
}

#11

17  

you could also go with regexps:

你也可以選擇regexp:

if((/^\s*$/).test(str)) { }

Checks for strings that are either empty or filled with whitespace.

檢查空的或填充空白的字串。

#12

13  

  1. check that var a; exist
  2. 檢查,var;存在
  3. trim out the false spaces in the value, then test for emptiness

    在值中去掉假空格,然後測試空值。

    if ((a)&&(a.trim()!=''))
    {
      // if variable a is not empty do this 
    }
    

#13

12  

A lot of answers, and a lot of different possibilities!

有很多答案,還有很多不同的可能性!

Without a doubt for quick and simple implementation the winner is: if (!str.length) {...}

毫無疑問,快速而簡單的實現方法是:if (! string .length){…}

However, as many other examples are available. The best functional method to go about this, I would suggest:

然而,還有許多其他的例子。最好的函式方法是,我建議:

function empty(str)
{
    if (typeof str == 'undefined' || !str || str.length === 0 || str === "" || !/[^\s]/.test(str) || /^\s*$/.test(str) || str.replace(/\s/g,"") === "")
    {
        return true;
    }
    else
    {
        return false;
    }
}

#14

11  

Also, in case you consider a whitespace filled string as "empty". You can test it with this Regex:

同樣,如果您認為空格填充的字串是“空的”。您可以使用這個Regex測試它:

!/\S/.test(string); // Returns true if blank.

#15

11  

You can use lodash : _.isEmpty(value).

您可以使用lodash: _.isEmpty(值)。

It covers a lot of cases like {}, '', null, undefined etc.

它涵蓋了許多像{},“,空,未定義等”的例子。

But it always returns true for Number type of Javascript Primitive Data Types like _.isEmpty(10) or _.isEmpty(Number.MAX_VALUE) both returns true.

但是,它總是返回true,用於Javascript原始資料型別,如_.isEmpty(10)或_.isEmpty(Number.MAX_VALUE)返回true。

#16

9  

I have not noticed an answer that takes into account the possibility of null characters in a string. For example, if we have a null character string:

我沒有注意到一個考慮到字串中空字元的可能性的答案。例如,如果我們有一個空字串:

var y = "\0"; // an empty string, but has a null character
(y === "") // false, testing against an empty string does not work
(y.length === 0) // false
(y) // true, this is also not expected
(y.match(/^[\s]*$/)) // false, again not wanted

To test its nullness one could do something like this:

為了測試它的零值,我們可以這樣做:

String.prototype.isNull = function(){ 
  return Boolean(this.match(/^[\0]*$/)); 
}
...
"\0".isNull() // true

It works on a null string, and on an empty string and it is accessible for all strings. In addition, it could be expanded to contain other JavaScript empty or whitespace characters (i.e. nonbreaking space, byte order mark, line/paragraph separator, etc.).

它在空字串上工作,並且在空字串上,它對所有字串都是可訪問的。此外,它還可以擴充套件為包含其他JavaScript空字元或空格字元(即不間斷空格、位元組順序標記、行/段落分隔符等)。

#17

9  

I usually use some thing like this,

我通常用這樣的東西,

if (!str.length) {
//do some thing
}

#18

8  

If one needs to detect not only empty but also blank strings, I'll add to Goral's answer:

如果需要檢測的不僅是空的字串,我還會新增Goral的答案:

function isEmpty(s){
    return !s.length;    
}

function isBlank(s){
    return isEmpty(s.trim());    
}

#19

7  

I use a combination, fastest checks are first.

我使用組合,最快的檢查是第一。

function isBlank(pString){
    if (!pString || pString.length == 0) {
        return true;
    }
    // checks for a non-white space character 
    // which I think [citation needed] is faster 
    // than removing all the whitespace and checking 
    // against an empty string
    return !/[^\s]+/.test(pString);
}

#20

7  

Ignoring whitespace strings, you could use this to check for null, empty and undefined :

忽略空白字串,可以使用它檢查null、空和未定義:

var obj = {};
(!!obj.str) //returns false

obj.str = "";
(!!obj.str) //returns false

obj.str = null;
(!!obj.str) //returns false

Concise and it works for undefined properties, although it's not the most readable.

簡潔,它適用於未定義的屬性,儘管它不是最易讀的。

#21

7  

All these answers are nice.

所有這些答案都很好。

But I cannot be sure that variable is a string, doesn't contains only spaces (this is important for me), and can contain '0' (string).

但是我不能確定變數是字串,不包含空格(這對我來說很重要),並且可以包含“0”(字串)。

My version:

我的版本:

function empty(str){
    return !str || !/[^\s]+/.test(str);
}

empty(null); // true
empty(0); // true
empty(7); // false
empty(""); // true
empty("0"); // false
empty("  "); // true

jsfiddle樣本。

#22

6  

I usually use something like:

我通常用:

if (str == "") {
     //Do Something
}
else {
     //Do Something Else
}

#23

6  

I did some research what happens if you pass a non-string and non-empty/null value to a tester function. As many knows, (0 == "") is true in javascript, but since 0 is a value and not empty or null, you may want to test for it.

我做了一些研究,如果您將一個非字串和非空/空值傳遞給測試函式,會發生什麼情況。正如許多人所知道的,(0 == ")在javascript中是正確的,但是由於0是一個值,而不是空的或空的,所以您可能想要測試它。

The following two functions return true only for undefined, null, empty/whitespace values and false for everything else, such as numbers, boolean, objects, expressions etc.

以下兩個函式只返回對未定義的、null、空/空格值和其他所有值的錯誤,如數字、布林、物件、表示式等。

function IsNullOrEmpty(value)
{
    return (value == null || value === "");
}
function IsNullOrWhiteSpace(value)
{
    return (value == null || !/\S/.test(value));
}

More complicated examples exists, but these are simple and give consistent results. There is no need to test for undefined, since it's included in (value == null) check. You may also mimic C# behaviour by adding them to String like this:

更復雜的例子是存在的,但是這些例子很簡單,並且給出了一致的結果。沒有必要對未定義的進行測試,因為它包含在(value == null)檢查中。您還可以通過將它們新增到字串中來模擬c#行為:

String.IsNullOrEmpty = function (value) { ... }

You do not want to put it in Strings prototype, because if the instance of the String-class is null, it will error:

您不希望將它放在字串原型中,因為如果string類的例項為null,那麼它將會出錯:

String.prototype.IsNullOrEmpty = function (value) { ... }
var myvar = null;
if (1 == 2) { myvar = "OK"; } // could be set
myvar.IsNullOrEmpty(); // throws error

I tested with the following value array. You can loop it through to test your functions if in doubt.

我使用以下值陣列進行了測試。如果有疑問,可以通過迴圈來測試函式。

// Helper items
var MyClass = function (b) { this.a = "Hello World!"; this.b = b; };
MyClass.prototype.hello = function () { if (this.b == null) { alert(this.a); } else { alert(this.b); } };
var z;
var arr = [
// 0: Explanation for printing, 1: actual value
    ['undefined', undefined],
    ['(var) z', z],
    ['null', null],
    ['empty', ''],
    ['space', ' '],
    ['tab', '\t'],
    ['newline', '\n'],
    ['carriage return', '\r'],
    ['"\\r\\n"', '\r\n'],
    ['"\\n\\r"', '\n\r'],
    ['" \\t \\n "', ' \t \n '],
    ['" txt \\t test \\n"', ' txt \t test \n'],
    ['"txt"', "txt"],
    ['"undefined"', 'undefined'],
    ['"null"', 'null'],
    ['"0"', '0'],
    ['"1"', '1'],
    ['"1.5"', '1.5'],
    ['"1,5"', '1,5'], // valid number in some locales, not in js
    ['comma', ','],
    ['dot', '.'],
    ['".5"', '.5'],
    ['0', 0],
    ['0.0', 0.0],
    ['1', 1],
    ['1.5', 1.5],
    ['NaN', NaN],
    ['/\S/', /\S/],
    ['true', true],
    ['false', false],
    ['function, returns true', function () { return true; } ],
    ['function, returns false', function () { return false; } ],
    ['function, returns null', function () { return null; } ],
    ['function, returns string', function () { return "test"; } ],
    ['function, returns undefined', function () { } ],
    ['MyClass', MyClass],
    ['new MyClass', new MyClass()],
    ['empty object', {}],
    ['non-empty object', { a: "a", match: "bogus", test: "bogus"}],
    ['object with toString: string', { a: "a", match: "bogus", test: "bogus", toString: function () { return "test"; } }],
    ['object with toString: null', { a: "a", match: "bogus", test: "bogus", toString: function () { return null; } }]
];

#24

6  

to check if is exactly an empty string:

檢查是否為空字串:

if(val==="")...

to check if it is an empty string OR a a logical equivalent for no-value (null, undefined, 0, NaN, false, ...):

檢查它是否是一個空字串或一個邏輯等價的無值(null,未定義,0,NaN, false,…):

if(!val)...

#25

5  

There's no isEmpty() method, you have to check for the type and the length:

沒有isEmpty()方法,您必須檢查型別和長度:

if (typeof test === 'string' && test.length === 0){
  ...

The type check is needed in order to avoid runtime errors when test is undefined or null.

當測試未定義或null時,需要型別檢查以避免執行時錯誤。

#26

5  

Try this

試試這個

   str.value.length == 0

#27

4  

function tell()
{
var pass = document.getElementById('pasword').value;
var plen = pass.length;

now you can check if your string is empty as like 
if(plen==0)
{
         alert('empty');
}
else
{
   alert('you entered something');
}
}


<input type='text' id='pasword' />

this is also a generic way to check if field is empty.

這也是檢查欄位是否為空的通用方法。

#28

4  

Don't assume that the variable you check is a string. Don't assume that if this var has a length, then it's a string.

不要假設您檢查的變數是字串。不要假設這個var有一個長度,那麼它就是一個字串。

The thing is: think carefully about what your app must do and can accept. Build something robust.

問題是:仔細考慮你的應用必須做什麼,並能接受。構建健壯的東西。

If your method / function should only process a non empty string then test if the argument is a non empty string and don't do some 'trick'.

如果您的方法/函式只處理一個非空字串,那麼測試引數是否為非空字串,並且不執行一些“技巧”。

As an example of something that will explode if you follow some advices here not carefully.

作為一個例子,如果你遵循一些建議將會爆炸,這裡不小心。


var getLastChar = function (str) {
 if (str.length > 0)
   return str.charAt(str.length - 1)
}

getLastChar('hello')
=> "o"

getLastChar([0,1,2,3])
=> TypeError: Object [object Array] has no method 'charAt'

So, I'd stick with

所以,我堅持


if (myVar === '')
  ...

#29

3  

You should always check for the type too, since JavaScript is a duck typed language, so you may not know when and how the data changed in the middle of the process. So, here's the better solution:

您也應該經常檢查型別,因為JavaScript是鴨子型別的語言,所以您可能不知道什麼時候以及如何在過程中間更改資料。所以,這裡有一個更好的解決方案:

var str = "";
if (str === "") {
    //...
}

#30

3  

The underscore javascript library http://underscorejs.org/ provides a very useful _.isEmpty() function for checking for empty strings and other empty objects.

下劃線javascript庫http://underscorejs.org/提供了一個非常有用的_.isEmpty()函式,用於檢查空字串和其他空物件。

參考:http://underscorejs.org/ isEmpty

isEmpty _.isEmpty(object)
Returns true if an enumerable object contains no values (no enumerable own-properties). For strings and array-like objects _.isEmpty checks if the length property is 0.

isEmpty _.isEmpty(物件)返回true,如果一個可列舉物件不包含值(沒有可列舉的自屬性)。對於字串和類似陣列的物件_。isEmpty檢查長度屬性是否為0。

_.isEmpty([1, 2, 3]);
=> false

_。isEmpty([1,2,3]);= >假

_.isEmpty({});
=> true

_.isEmpty({ });= > true

其他非常有用的下劃線函式包括:http://underscorejs.org/#isNull _.isNull(物件)http://underscorejs.org/#isUndefined _.isUndefined(value) http://underscorejs.org/#有_。(物件,鍵)


轉載請註明本文地址:How do you check for an empty string in JavaScript?