Come controllare la stringa vuota / non definita / null in JavaScript?
-
03-07-2019 - |
Domanda
Ho visto questo thread , ma io non ho visto un esempio specifico di JavaScript. Esiste una semplice string.Empty
disponibile in JavaScript o è solo un caso di controllo per " "
?
Soluzione
Se vuoi solo verificare se c'è qualche valore, puoi farlo
if (strValue) {
//do something
}
Se hai bisogno di controllare specificatamente una stringa vuota su null, penso che il controllo su " "
sia la soluzione migliore, usando l'operatore ===
(in modo da sapere che in realtà è una stringa con cui stai confrontando ).
if (strValue === "") {
//...
}
Altri suggerimenti
Per verificare se una stringa è vuota, nulla o non definita, utilizzo:
function isEmpty(str) {
return (!str || 0 === str.length);
}
Per verificare se una stringa è vuota, nulla o non definita, utilizzo:
function isBlank(str) {
return (!str || /^\s*$/.test(str));
}
Per verificare se una stringa è vuota o contiene solo spazi bianchi:
String.prototype.isEmpty = function() {
return (this.length === 0 || !this.trim());
};
Tutto quanto sopra è buono, ma sarà ancora meglio. usa l'operatore !!
( not not ).
if(!!str){
some code here;
}
o usa il tipo casting:
if(Boolean(str)){
codes here;
}
Entrambi svolgono la stessa funzione, digita cast la variabile in booleano, dove str
è una variabile.
Restituisce false
per null, undefined, 0,000, " ", false
.
Restituisce true
per stringa " 0 " e spazi bianchi " & Quot;.
Se devi assicurarti che la stringa non sia solo un mucchio di spazi vuoti (suppongo che questo sia per la validazione del modulo) devi fare una sostituzione sugli spazi.
if(str.replace(/\s/g,"") == ""){
}
La cosa più vicina a str.Empty
(con il presupposto che str sia una stringa) è:
if (!str.length) { ...
Uso:
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
Prova:
if (str && str.trim().length) {
//...
}
funzione:
function is_empty(x)
{
return (
(typeof x == 'undefined')
||
(x == null)
||
(x == false) //same as: !x
||
(x.length == 0)
||
(x == "")
||
(x.replace(/\s/g,"") == "")
||
(!/[^\s]/.test(x))
||
(/^\s*$/.test(x))
);
}
P.S. In Javascript, non utilizzare l'interruzione di riga dopo
return
;
var s; // undefined
var s = ""; // ""
s.length // 0
Non c'è nulla che rappresenti una stringa vuota in JavaScript. Fai un controllo o length
(se sai che var sarà sempre una stringa) o contro ""
Puoi utilizzare lodash : _.isEmpty (valore).
Copre molti casi come {}
, ''
, null
, undefined
ecc.
Ma restituisce sempre true
per il tipo Number
di Tipi di dati primitivi Javascript come _.isEmpty (10)
o _.isEmpty (Number.MAX_VALUE)
entrambi restituiscono < code> true .
Non mi preoccuperei troppo del metodo più efficiente . Usa ciò che è più chiaro alla tua intenzione. Per me questo è di solito strVar == " "
.
EDIT: per commento da Constantin , se strVar potesse in qualche modo finire con contenere un valore intero 0, allora sarebbe in effetti, è una di quelle situazioni che chiariscono l'intenzione.
potresti anche usare regexps:
if((/^\s*$/).test(str)) { }
Verifica le stringhe vuote o piene di spazi bianchi.
Molte risposte e molte possibilità diverse!
Senza dubbio per un'implementazione rapida e semplice il vincitore è: if (! str.length) {...}
Tuttavia, come molti altri esempi sono disponibili. Il miglior metodo funzionale per farlo, suggerirei:
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;
}
}
Un po 'eccessivo, lo so.
- controlla che
var a;
esista -
ritaglia il
spazi falsi
nel valore, quindi verificaemptiness
if ((a)&&(a.trim()!='')) { // if variable a is not empty do this }
Inoltre, nel caso in cui consideri una stringa riempita di spazi bianchi come " vuoto " ;. Puoi provarlo con questo Regex:
!/\S/.test(string); // Returns true if blank.
Di solito uso qualcosa del genere,
if (!str.length) {
//do some thing
}
Non ho notato una risposta che tenga conto della possibilità di caratteri null in una stringa. Ad esempio, se abbiamo una stringa di caratteri 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
Per testarne la nullità si potrebbe fare qualcosa del genere:
String.prototype.isNull = function(){
return Boolean(this.match(/^[\0]*$/));
}
...
"\0".isNull() // true
Funziona su una stringa nulla e su una stringa vuota ed è accessibile per tutte le stringhe. Inoltre, potrebbe essere espanso per contenere altri caratteri vuoti o bianchi di JavaScript (ad es. Spazio non di rottura, segno di ordine byte, separatore di riga / paragrafo, ecc.).
Se è necessario rilevare non solo stringhe vuote ma anche vuote, aggiungerò alla risposta di Goral:
function isEmpty(s){
return !s.length;
}
function isBlank(s){
return isEmpty(s.trim());
}
Tutte queste risposte sono belle.
Ma non posso essere sicuro che la variabile sia una stringa, non contenga solo spazi (questo è importante per me) e può contenere '0' (stringa).
La mia versione:
function empty(str){
return !str || !/[^\s]+/.test(str);
}
empty(null); // true
empty(0); // true
empty(7); // false
empty(""); // true
empty("0"); // false
empty(" "); // true
Esempio su jsfiddle .
Di solito uso qualcosa del tipo:
if (str == "") {
//Do Something
}
else {
//Do Something Else
}
Uso una combinazione, i controlli più veloci sono i primi.
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);
}
Ignorando le stringhe di spazi bianchi, puoi usarlo per verificare la presenza di null, vuoti e indefiniti:
var obj = {};
(!!obj.str) //returns false
obj.str = "";
(!!obj.str) //returns false
obj.str = null;
(!!obj.str) //returns false
Conciso e funziona con proprietà indefinite, sebbene non sia il più leggibile.
Ho fatto qualche ricerca su cosa succede se si passa un valore non stringa e non vuoto / null a una funzione tester. Come molti sanno, (0 == " ") è vero in javascript, ma poiché 0 è un valore e non è vuoto o nullo, potresti voler provarlo.
Le seguenti due funzioni restituiscono true solo per valori indefiniti, null, vuoti / bianchi e false per tutto il resto, come numeri, valori booleani, oggetti, espressioni ecc.
function IsNullOrEmpty(value)
{
return (value == null || value === "");
}
function IsNullOrWhiteSpace(value)
{
return (value == null || !/\S/.test(value));
}
Esistono esempi più complicati, ma questi sono semplici e danno risultati coerenti. Non è necessario verificare se non definito, poiché è incluso nel controllo (valore == null). Puoi anche imitare il comportamento di C # aggiungendoli a String in questo modo:
String.IsNullOrEmpty = function (value) { ... }
Non si desidera inserirlo nel prototipo di Stringhe, poiché se l'istanza della classe String è nulla, si verificherà un errore:
String.prototype.IsNullOrEmpty = function (value) { ... }
var myvar = null;
if (1 == 2) { myvar = "OK"; } // could be set
myvar.IsNullOrEmpty(); // throws error
Ho provato con il seguente array di valori. Puoi collegarlo in loop per testare le tue funzioni in caso di dubbio.
// 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; } }]
];
per verificare se è esattamente una stringa vuota:
if(val==="")...
per verificare se è una stringa vuota O un equivalente logico per nessun valore (null, non definito, 0, NaN, false, ...):
if(!val)...
Nel frattempo possiamo avere una funzione che controlla tutti gli "vuoti" come null, undefined, '', '', {}, [] . Quindi ho appena scritto questo.
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;
}
}
Usa casi e risultati.
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
Non esiste un metodo isEmpty ()
, devi verificare il tipo e la lunghezza:
if (typeof test === 'string' && test.length === 0){
...
Il controllo del tipo è necessario per evitare errori di runtime quando test
è non definito
o null
.
Non dare per scontato che la variabile che controlli sia una stringa. Non dare per scontato che se questo var ha una lunghezza, allora è una stringa.
Il fatto è: pensa attentamente a ciò che la tua app deve fare e può accettare. Costruisci qualcosa di robusto.
Se il tuo metodo / funzione deve elaborare solo una stringa non vuota, verifica se l'argomento è una stringa non vuota e non eseguire alcun "trucco".
Come esempio di qualcosa che esploderà se segui alcuni consigli qui non attentamente.
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'
Quindi, starei con
if (myVar === '')
...
Prova questo
str.value.length == 0
Puoi facilmente aggiungerlo all'oggetto String nativo in JavaScript e riutilizzarlo più volte ...
Qualcosa di semplice come il codice qui sotto può fare il lavoro per te se vuoi controllare ''
stringhe vuote:
String.prototype.isEmpty = String.prototype.isEmpty || function() {
return !(!!this.length);
}
Altrimenti, se desideri controllare sia ''
stringa vuota sia ''
con spazio, puoi aggiungere semplicemente trim ()
, qualcosa come il codice qui sotto:
String.prototype.isEmpty = String.prototype.isEmpty || function() {
return !(!!this.trim().length);
}
e puoi chiamarlo in questo modo:
''.isEmpty(); //return true
'alireza'.isEmpty(); //return false
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' />
questo è anche un modo generico per verificare se il campo è vuoto.