Jak mogę sprawdzić pusty/niezdefiniowany / null łańcuch w JavaScript?

Widziałem to pytanie , ale nie widziałem konkretnego przykładu JavaScript. Czy istnieje prosta string.Empty dostępna w JavaScript, czy tylko sprawdzanie ""?

Author: Peter Mortensen, 2008-09-30

30 answers

Jeśli chcesz tylko sprawdzić, czy jest jakaś wartość, możesz zrobić

if (strValue) {
    //do something
}

Jeśli chcesz sprawdzić pusty łańcuch nad null, myślę, że sprawdzanie przed "" jest najlepszym rozwiązaniem, używając operatora === (aby wiedzieć, że jest to w rzeczywistości łańcuch, z którym porównujesz).

if (strValue === "") {
    //...
}
 3916
Author: bdukes,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-06-02 00:29:22

Do sprawdzania czy łańcuch jest pusty, null lub undefined używam:

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

Do sprawdzania czy łańcuch jest pusty, null lub undefined używam:

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

Do sprawdzania, czy łańcuch jest pusty lub zawiera tylko białą spację:

String.prototype.isEmpty = function() {
    return (this.length === 0 || !this.trim());
};
 1204
Author: Jano González,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-05-13 14:00:33

Wszystkie poprzednie odpowiedzi są dobre, ale to będzie jeszcze lepsze. Używaj operatorów dual NOT (!!):

if (!!str) {
    // Some code here
}

Lub użyć odlewu typu:

if (Boolean(str)) {
    // Code here
}

Obie wykonują tę samą funkcję. Typuj zmienną na Boolean, gdzie str jest zmienną.
Zwraca false dla null, undefined, 0, 000, "", false.
Zwraca true dla string "0" i whitespace " ".

 380
Author: karthick.sk,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-11-11 06:25:29

Najbliższą rzeczą, do której możesz się dostać str.Empty (z warunkiem, że str jest ciągiem znaków) jest:

if (!str.length) { ...
 114
Author: Ates Goral,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-08-31 16:08:28

Jeśli chcesz się upewnić, że ciąg znaków nie jest tylko zbiorem pustych spacji (zakładam, że jest to Walidacja formularza), musisz wykonać zastąpienie spacji.

if(str.replace(/\s/g,"") == ""){
}
 106
Author: Sugendran,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2008-09-30 23:08:32

Używam:

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

empty(null) // true
empty(0) // true
empty(7) // false
empty("") // true
empty((function() {
    return ""
})) // false
 70
Author: Jet,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-03-08 23:39:58

Możesz użyć lodash : _.isEmpty (wartość).

Obejmuje wiele spraw, takich jak {}, '', null, undefined, itd.

Ale zawsze zwraca true dla Number typu JavaScript prymitywne typy danych jak _.isEmpty(10) lub _.isEmpty(Number.MAX_VALUE) oba zwracają true.

 49
Author: Moshii,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-03-09 00:17:54

Bardzo ogólna funkcja" All-In-One " (nie jest jednak zalecana):

function is_empty(x)
{
    return (                                                           //don't put newline after return
        (typeof x == 'undefined')
              ||
        (x == null)
              ||
        (x == false)        //same as: !x
              ||
        (x.length == 0)
              ||
        (x == 0)            // note this line, you might not need this. 
              ||
        (x == "")
              ||
        (x.replace(/\s/g,"") == "")
              ||
        (!/[^\s]/.test(x))
              ||
        (/^\s*$/.test(x))
    );
}

Jednak nie polecam tego używać, ponieważ twoja zmienna docelowa powinna być określonego typu(np.), więc zastosuj kontrole, które są względem tej zmiennej.

 42
Author: T.Todua,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-10-07 00:57:10

Wydajność

Wykonuję testy na macOS v10.13.6 (High Sierra) dla 18 wybranych rozwiązań. Rozwiązania działają nieco inaczej (dla danych wejściowych), co zostało przedstawione w poniższym fragmencie.

Wnioski

  • proste rozwiązania oparte na !str,==,=== i length są szybkie dla wszystkich przeglądarek (A,B,C,G,I,J)
  • rozwiązania oparte na wyrażeniu regularnym(test,replace) i charAt są najwolniejsze dla wszystkich przeglądarek (H, L,M, P)
  • Rozwiązania oznaczone jako najszybsze były najszybsze tylko w jednym przejeździe testowym - ale w wielu przejazdach zmieniają się w grupie "szybkich" rozwiązań.]}

Tutaj wpisz opis obrazka

Szczegóły

W poniższym fragmencie porównuję wyniki wybranych 18 metod używając różnych parametrów wejściowych

  • "" "a" " "- pusty łańcuch, łańcuch z literą i łańcuch ze spacją
  • [] {} f- array, object and function
  • 0 1 NaN Infinity - liczby
  • true false - Boolean
  • null undefined

Nie wszystkie testowane metody obsługują wszystkie przypadki wejścia.

function A(str) {
  let r=1;
  if (!str)
    r=0;
  return r;
}

function B(str) {
  let r=1;
  if (str == "")
    r=0;
  return r;
}

function C(str) {
  let r=1;
  if (str === "")
    r=0;
  return r;
}

function D(str) {
  let r=1;
  if(!str || 0 === str.length)
    r=0;
  return r;
}

function E(str) {
  let r=1;
  if(!str || /^\s*$/.test(str))
    r=0;
  return r;
}

function F(str) {
  let r=1;
  if(!Boolean(str))
    r=0;
  return r;
}

function G(str) {
  let r=1;
  if(! ((typeof str != 'undefined') && str) )
    r=0;
  return r;
}

function H(str) {
  let r=1;
  if(!/\S/.test(str))
    r=0;
  return r;
}

function I(str) {
  let r=1;
  if (!str.length)
    r=0;
  return r;
}

function J(str) {
  let r=1;
  if(str.length <= 0)
    r=0;
  return r;
}

function K(str) {
  let r=1;
  if(str.length === 0 || !str.trim())
    r=0;
  return r;
}

function L(str) {
  let r=1;
  if ( str.replace(/\s/g,"") == "")
    r=0;
  return r;
}

function M(str) {
  let r=1;
  if((/^\s*$/).test(str))
    r=0;
  return r;
}


function N(str) {
  let r=1;
  if(!str || !str.trim().length)
    r=0;
  return r;
}

function O(str) {
  let r=1;
  if(!str || !str.trim())
    r=0;
  return r;
}

function P(str) {
  let r=1;
  if(!str.charAt(0))
    r=0;
  return r;
}

function Q(str) {
  let r=1;
  if(!str || (str.trim()==''))
    r=0;
  return r;
}

function R(str) {
  let r=1;
  if (typeof str == 'undefined' ||
      !str ||
      str.length === 0 ||
      str === "" ||
      !/[^\s]/.test(str) ||
      /^\s*$/.test(str) ||
      str.replace(/\s/g,"") === "")

    r=0;
  return r;
}




// --- TEST ---

console.log(                  '   ""  "a"  " " [] {} 0 1 NaN Infinity f true false null undefined ');
let log1 = (s,f)=> console.log(`${s}: ${f("")}   ${f("a")}    ${f(" ")}   ${f([])}  ${f({})}  ${f(0)} ${f(1)} ${f(NaN)}   ${f(Infinity)}        ${f(f)} ${f(true)}    ${f(false)}     ${f(null)}    ${f(undefined)}`);
let log2 = (s,f)=> console.log(`${s}: ${f("")}   ${f("a")}    ${f(" ")}   ${f([])}  ${f({})}  ${f(0)} ${f(1)} ${f(NaN)}   ${f(Infinity)}        ${f(f)} ${f(true)}    ${f(false)}`);
let log3 = (s,f)=> console.log(`${s}: ${f("")}   ${f("a")}    ${f(" ")}`);

log1('A', A);
log1('B', B);
log1('C', C);
log1('D', D);
log1('E', E);
log1('F', F);
log1('G', G);
log1('H', H);

log2('I', I);
log2('J', J);

log3('K', K);
log3('L', L);
log3('M', M);
log3('N', N);
log3('O', O);
log3('P', P);
log3('Q', Q);
log3('R', R);

A następnie dla wszystkich metod wykonuję przypadek speed test str = "" dla przeglądarek Chrome v78.0.0, Safari v13.0.4 i Firefox v71.0.0 - możesz uruchomić testy na swoim komputerze tutaj

Tutaj wpisz opis obrazka

 39
Author: Kamil Kiełczewski,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-03-09 06:03:44
var s; // undefined
var s = ""; // ""
s.length // 0

Nie ma nic reprezentującego pusty łańcuch w JavaScript. Wykonaj sprawdzenie przeciwko length (jeśli wiesz, że var zawsze będzie ciągiem znaków) lub przeciwko ""

 38
Author: cllpse,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2008-09-30 17:42:32

Try:

if (str && str.trim().length) {  
    //...
}
 38
Author: Yang Dong,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-01-09 03:15:06

Nie martwiłbym się zbytnio o najbardziej efektywną metodę. Użyj tego, co jest najbardziej jasne dla Twojej intencji. Dla mnie to zazwyczaj strVar == "".

Zgodnie z komentarzem z Constantin , jeśli strVar może jakiś sposób skończyć zawierające wartość całkowitą 0, to rzeczywiście byłoby to jedną z tych intencji-wyjaśnienie sytuacji.

 31
Author: Chris Noe,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-03-08 23:39:03

Można też używać wyrażeń regularnych:

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

Sprawdza, czy ciągi znaków są puste lub wypełnione białymi znakami.

 22
Author: oem,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-03-08 23:39:37
  1. sprawdź czy var a; Istnieją
  2. Trim out false spaces in the value, then test for emptiness

    if ((a)&&(a.trim()!=''))
    {
      // if variable a is not empty do this 
    }
    
 21
Author: Timothy Nwanwene,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-09-07 07:58:24

Wiele odpowiedzi i wiele różnych możliwości!

Bez wątpienia dla szybkiej i prostej realizacji zwycięzcą jest: if (!str.length) {...}

Jednak, jak wiele innych przykładów jest dostępnych. Najlepsza funkcjonalna metoda, aby to zrobić, sugerowałbym:

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;
}
Wiem, że trochę przesadnie.
 21
Author: tfont,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-11-03 12:10:24

Również, jeśli uznasz, że wypełniony białymi znakami łańcuch jest "pusty".

Możesz go przetestować za pomocą tego wyrażenia regularnego:

!/\S/.test(string); // Returns true if blank.
 17
Author: Wab_Z,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-03-08 23:55:40

Zwykle używam czegoś takiego,

if (!str.length) {
    // Do something
}
 16
Author: user2086641,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-03-08 23:58:54

Jeśli trzeba wykryć nie tylko puste, ale i puste ciągi, dodam do Gorala odpowiedź:

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

function isBlank(s){
    return isEmpty(s.trim());    
}
 13
Author: Josef.B,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-10-01 06:55:13

Zaczynając od:

return (!value || value == undefined || value == "" || value.length == 0);

Patrząc na ostatni warunek, jeśli wartość=="", jego długość musi być równa 0. Dlatego upuść:

return (!value || value == undefined || value == "");
Ale czekaj! W JavaScript pusty łańcuch jest false. Zatem wartość kropli=="":
return (!value || value == undefined);

I !undefined jest true, więc to sprawdzenie nie jest potrzebne. Więc mamy:

return (!value);

I nie potrzebujemy nawiasów:

return !value
 12
Author: Abhishek Luthra,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-03-09 00:28:59

Nie zauważyłem odpowiedzi, która uwzględnia możliwość wystąpienia znaków null w łańcuchu. Na przykład, jeśli mamy łańcuch znaków null:

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

Aby sprawdzić jego nieważność można zrobić coś takiego:

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

Działa na łańcuchu null oraz na pustym łańcuchu i jest dostępny dla wszystkich łańcuchów. Ponadto może być rozszerzony o inne puste lub białe znaki JavaScript (np. niełamliwe spacje, znak kolejności bajtów, separator linii/akapitu, itd.).

 11
Author: Bikush,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-07-31 14:05:04

Tymczasem możemy mieć jedną funkcję, która sprawdza wszystkie "pustki" jak null, undefined, ", ' ', {}, []. Więc właśnie to napisałem.

var isEmpty = function(data) {
    if(typeof(data) === 'object'){
        if(JSON.stringify(data) === '{}' || JSON.stringify(data) === '[]'){
            return true;
        }else if(!data){
            return true;
        }
        return false;
    }else if(typeof(data) === 'string'){
        if(!data.trim()){
            return true;
        }
        return false;
    }else if(typeof(data) === 'undefined'){
        return true;
    }else{
        return false;
    }
}

Przypadki użycia i wyniki.

console.log(isEmpty()); // true
console.log(isEmpty(null)); // true
console.log(isEmpty('')); // true
console.log(isEmpty('  ')); // true
console.log(isEmpty(undefined)); // true
console.log(isEmpty({})); // true
console.log(isEmpty([])); // true
console.log(isEmpty(0)); // false
console.log(isEmpty('Hey')); // false
 11
Author: Imran Ahmad,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-03-12 08:48:23

Na razie nie ma bezpośredniej metody jak string.empty, aby sprawdzić, czy łańcuch jest pusty, czy nie. Ale w kodzie możesz użyć wrapper check dla pustego ciągu jak:

// considering the variable in which your string is saved is named str.

if (str && str.length>0) { 

  // Your code here which you want to run if the string is not empty.

}

Używając tego możesz również upewnić się, że string nie jest undefined ani null. Pamiętaj, undefined, null i empty to trzy różne rzeczy.

 11
Author: Harshit Agarwal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-09-03 08:25:08

Nie widziałem tu dobrej odpowiedzi (przynajmniej nie odpowiadającej Mi)

Więc postanowiłem odpowiedzieć sobie:

value === undefined || value === null || value === "";

Musisz zacząć sprawdzać, czy jest niezdefiniowany. W przeciwnym razie twoja metoda może eksplodować, a następnie możesz sprawdzić, czy jest równa null lub jest równa pustemu łańcuchowi.

Nie możesz !! lub tylko if(value), ponieważ jeśli sprawdzisz 0, otrzymasz fałszywą odpowiedź (0 to fałsz). / Align = "left" / like:

public static isEmpty(value: any): boolean { return value === undefined || value === null || value === ""; }

PS.: nie musisz sprawdzać typeof, ponieważ eksploduje i rzuca nawet przed wejściem do metody

 11
Author: Davi Daniel Siepmann,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-03-09 00:21:21

Wszystkie te odpowiedzi są miłe.

Ale nie mogę być pewien, że zmienna jest ciągiem znaków, nie zawiera tylko spacji (jest to dla mnie ważne) i może zawierać '0' (string).

Moja Wersja:

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

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

Próbka na jsfiddle .

 10
Author: Andron,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-03-08 23:52:19

Aby sprawdzić, czy jest to dokładnie pusty łańcuch:

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

Aby sprawdzić, czy jest to pusty łańcuch lub logiczny odpowiednik Dla no-value (null, undefined, 0, Nan, false,...):

if(!val)...
 10
Author: Luca C.,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-03-09 00:16:34

Spróbuj tego:

export const isEmpty = string => (!string || !string.length);
 9
Author: V1NNY,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-06-14 11:01:01

Zrobiłem kilka badań na temat tego, co się stanie, jeśli przekażesz wartość non-string i niepustą / null do funkcji testera. Jak wielu wie, (0 == "") jest prawdą w JavaScript, ale ponieważ 0 jest wartością, a nie pustą lub null, możesz chcieć ją przetestować.

Następujące dwie funkcje zwracają true tylko dla wartości undefined, null, empty / whitespace i false dla wszystkich innych, takich jak liczby, logiczne, obiekty, wyrażenia, itp.

function IsNullOrEmpty(value)
{
    return (value == null || value === "");
}
function IsNullOrWhiteSpace(value)
{
    return (value == null || !/\S/.test(value));
}
Istnieją bardziej skomplikowane przykłady, ale są one proste i dawać spójne wyniki. Nie ma potrzeby testowania undefined, ponieważ jest zawarte w (value == null) check. Możesz również naśladować zachowanie C# dodając je do ciągu znaków w następujący sposób:
String.IsNullOrEmpty = function (value) { ... }

Nie chcesz umieszczać tego w prototypie Strings, ponieważ jeśli instancja klasy String jest null, spowoduje to błąd:

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

Testowałem z poniższą tablicą wartości. Możesz go zapętlić, aby przetestować swoje funkcje, jeśli masz wątpliwości.

// 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 JavaScript
    ['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; } }]
];
 9
Author: JHM,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-03-08 23:55:10

Nie ma metody isEmpty(), musisz sprawdzić typ i długość:

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

Sprawdzanie typu jest konieczne, aby uniknąć błędów podczas pracy, gdy test jest undefined lub null.

 8
Author: Agustí Sánchez,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-11-04 22:28:45

Spróbuj tego

str.value.length == 0
 8
Author: Doug,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-01-08 04:39:59

Możesz łatwo dodać go do natywnego obiektu String W JavaScript i ponownie używać go w kółko...
Coś prostego jak poniższy kod może wykonać zadanie za Ciebie, jeśli chcesz sprawdzić '' puste ciągi:

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

W przeciwnym razie, jeśli chcesz sprawdzić zarówno '' pusty łańcuch, jak i ' ' ze spacją, możesz to zrobić, dodając trim(), coś w stylu poniższego kodu:

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

I można to nazwać w ten sposób:

''.isEmpty(); //return true
'alireza'.isEmpty(); //return false
 8
Author: Alireza,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-01-19 06:19:06