Jak sprawdzić pusty łańcuch w JavaScript?

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

Author: Community, 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 === "") {
    //...
}
 2793
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());
};
 916
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 powyższe są dobre, ale to będzie jeszcze lepsze. użycie !!(Nie Nie ) operator.

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

Lub użyć odlewu typu:

if(Boolean(str)){
    codes 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 ciągu znaków " 0 "i białych znaków"".

 232
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
2012-04-03 09:11:41

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,"") == ""){
}
 89
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

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

Używam:

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
 46
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
2017-11-13 17:11:42
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 ""

 24
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) {  
    //...
}
 23
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 == "".

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

 22
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
2017-05-23 11:47:32

Funkcja:

function Is_Empty_or_Undefined (MyVar)
{
   return 
   ( 
        (typeof MyVar== 'undefined')
                    ||
        (MyVar == null) 
                    ||
        (MyVar == false)  //same as: !MyVariable
                    ||
        (MyVar.length == 0)
                    ||
        (MyVar == "")
                    ||
        (MyVar.replace(/\s/g,"") == "")
                    ||
        (!/[^\s]/.test(MyVar))
                    ||
        (/^\s*$/.test(MyVar))
  );
}
 21
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
2018-08-22 09:44:47

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.

 19
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
2018-03-08 12:55:29

Możesz również użyć wyrażeń regularnych:

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

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

 17
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
2010-05-31 14:57:38
  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 
    }
    
 13
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.
 12
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
2018-09-14 08:25:45

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.
 11
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
2013-05-15 14:55:15

Zwykle używam czegoś takiego,

if (!str.length) {
//do some thing
}
 10
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
2013-08-09 10:10:50

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

 9
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

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

Używam kombinacji, najszybsze kontrole są pierwsze.

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);
}
 7
Author: Will,
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
2011-06-01 15:40:33

Ignorując ciągi znaków spacji, możesz użyć tego do sprawdzenia null, empty i undefined:

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

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

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

Zwięzły i działa dla niezdefiniowanych właściwości, chociaż nie jest najbardziej czytelny.

 7
Author: mricci,
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-10-11 02:56:13

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 .

 7
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
2013-05-08 17:15:40

Zwykle używam czegoś w stylu:

if (str == "") {
     //Do Something
}
else {
     //Do Something Else
}
 6
Author: jmc734,
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
2010-02-15 02:46:49

Zrobiłem kilka badań, 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, logika logiczna, 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żna 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 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; } }]
];
 6
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
2013-05-14 10:18:36

Aby sprawdzić, czy jest 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)...
 6
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
2017-06-02 08:33:53

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.

 5
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
 5
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
2017-10-30 14:28:50

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
 5
Author: Imran,
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
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' />

Jest to również ogólny sposób sprawdzenia, czy pole jest puste.

 4
Author: Muhammad Salman,
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
2010-08-06 16:28:06

Nie zakładaj, że zmienna, którą sprawdzasz, jest łańcuchem znaków. Nie zakładaj, że jeśli ten var ma długość, to jest ciągiem znaków.

Rzecz w tym, że: zastanów się dokładnie, co Twoja aplikacja musi zrobić i może zaakceptować. Zbuduj coś solidnego.

Jeśli twoja metoda / funkcja powinna przetwarzać tylko niepusty łańcuch znaków, sprawdź, czy argument jest niepustym łańcuchem znaków i nie rób jakiegoś 'triku'.

Jako przykład czegoś, co wybuchnie, jeśli zastosujesz się do niektórych porad tutaj nie ostrożnie.


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'

Więc zostałbym przy

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

 4
Author: Amida,
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-07-15 10:55:44

Należy zawsze sprawdzać również Typ, ponieważ JavaScript jest językiem pisanym kaczką, więc możesz nie wiedzieć, kiedy i jak dane zmieniły się w środku procesu. Więc, tutaj jest lepsze rozwiązanie:

var str = "";
if (str === "") {
    //...
}
 3
Author: Sazid,
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-06 06:38:00