pat*_*tad 124 javascript string whitespace
What is the best way to check if a string contains only whitespace?
The string is allowed to contain characters combined with whitespace, but not just whitespace.
nic*_*ckf 283
而不是检查整个字符串以查看是否只有空格,只需检查是否至少有一个非空格字符:
if (/\S/.test(myString)) {
// string is not empty and not just whitespace
}
Run Code Online (Sandbox Code Playgroud)
Pau*_*sey 33
if (/^\s+$/.test(myString))
{
//string contains only whitespace
}
Run Code Online (Sandbox Code Playgroud)
这将检查一个或多个空格字符,如果它也匹配一个空字符串,则替换+为*.
Ful*_*ack 28
如果您的浏览器支持该trim()功能,最简单的答案
if (myString && !myString.trim()) {
//First condition to check if string is not empty
//Second condition checks if string contains just whitespace
}
Run Code Online (Sandbox Code Playgroud)
Day*_*son 18
好吧,如果你使用的是jQuery,那就更简单了.
if ($.trim(val).length === 0){
// string is invalid
}
Run Code Online (Sandbox Code Playgroud)
只需检查此正则表达式的字符串:
if(mystring.match(/^\s+$/) === null) {
alert("String is good");
} else {
alert("String contains only whitespace");
}
Run Code Online (Sandbox Code Playgroud)