繁体   English   中英

如何检查字符串是否包含字符和空格,而不仅仅是空格?

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

检查字符串是否仅包含空格的最佳方法是什么?

该字符串允许包含与空格组合的字符,但不仅仅是空格。

与其检查整个字符串以查看是否只有空格,只需检查是否至少有一个空格字符:

if (/\S/.test(myString)) {
    // string is not empty and not just whitespace
}

如果您的浏览器支持trim()函数,那么最简单的答案

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
}

这会检查 1 个或多个空白字符,如果您还匹配空字符串,则将+替换为*

好吧,如果您使用的是 jQuery,那就更简单了。

if ($.trim(val).length === 0){
   // string is invalid
} 

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

if(mystring.match(/^\s+$/) === null) {
    alert("String is good");
} else {
    alert("String contains only whitespace");
}
if (!myString.replace(/^\s+|\s+$/g,""))
  alert('string is only whitespace');

当我想在字符串中间允许空格但不在开头或结尾时,我最终使用的正则表达式是这样的:

[\S]+(\s[\S]+)*

^[\S]+(\s[\S]+)*$

所以,我知道这是一个老问题,但你可以这样做:

if (/^\s+$/.test(myString)) {
    //string contains characters and white spaces
}

或者你可以做nickf所说的并使用:

if (/\S/.test(myString)) {
    // string is not empty and not just whitespace
}

我使用以下方法来检测字符串是否仅包含空格。 它还匹配空字符串。

if (/^\s*$/.test(myStr)) {
  // the string contains only whitespace
}

这可以是快速解决方案

return input < "\u0020" + 1;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM