How can I check if string contains characters & whitespace, not just whitespace?

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)

  • 请注意myString为null值.它将返回true:/\ S/.test(null)== true (6认同)
  • 很多这些答案都有正则表达式!这是否意味着没有本地方法来检测js中的东西?没有string.IsWhitespace还是什么?还没有原生装饰吗? (5认同)
  • @JonnyLeeds由于正则表达式甚至在js中都支持语法,因此可以说它实际上比任何附带的实用程序方法都更本机;) (3认同)

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)

  • 也适用于换行符和制表符,而上面的正则表达式示例则不然,因为它们只是寻找除空格之外的任何内容。尽管如此,我确信具有一定正则表达式知识的人可以创建一个正则表达式,该正则表达式还将在搜索中包含制表符/换行符。 (2认同)

Ian*_*and 6

只需检查此正则表达式的字符串:

if(mystring.match(/^\s+$/) === null) {
    alert("String is good");
} else {
    alert("String contains only whitespace");
}
Run Code Online (Sandbox Code Playgroud)