Risposte:
Invece di controllare l'intera stringa per vedere se c'è solo spazio, controlla solo se c'è almeno un carattere di spazio non bianco:
if (/\S/.test(myString)) {
// string is not empty and not just whitespace
}
Risposta più semplice se il browser supporta la trim()
funzione
if (myString && !myString.trim()) {
//First condition to check if string is not empty
//Second condition checks if string contains just whitespace
}
if (/^\s+$/.test(myString))
{
//string contains only whitespace
}
questo controlla 1 o più caratteri di spazi bianchi, se si deve anche abbinare una stringa vuota, sostituire +
con *
.
Bene, se stai usando jQuery, è più semplice.
if ($.trim(val).length === 0){
// string is invalid
}
Basta controllare la stringa con questo regex:
if(mystring.match(/^\s+$/) === null) {
alert("String is good");
} else {
alert("String contains only whitespace");
}
L'espressione regolare che ho usato per quando voglio consentire spazi nel mezzo della mia stringa, ma non all'inizio o alla fine era questa:
[\S]+(\s[\S]+)*
o
^[\S]+(\s[\S]+)*$
Quindi, so che questa è una vecchia domanda, ma potresti fare qualcosa del tipo:
if (/^\s+$/.test(myString)) {
//string contains characters and white spaces
}
oppure puoi fare quello che ha detto Nickf e usare:
if (/\S/.test(myString)) {
// string is not empty and not just whitespace
}
Ho usato il seguente metodo per rilevare se una stringa contiene solo spazi bianchi. Corrisponde anche a stringhe vuote.
if (/^\s*$/.test(myStr)) {
// the string contains only whitespace
}
Questa può essere una soluzione veloce
return input < "\u0020" + 1;
return input < " 1";
Che sta solo facendo un confronto alfabetico. Fintanto che l'input viene ordinato più in basso di "1", restituirà true. Esempio: return " asdfv34562345" < "\u0020" + 1;
restituisce vero.