如何使用javascript确定字符串是否只包含空格?

如何使用javascript确定字符串是否只包含空格?,javascript,jquery,Javascript,Jquery,如何使用javascript确定输入字符串是否只包含空格?另一篇好文章: 您只需要应用函数并检查字符串的长度。如果修剪后的长度为0-则字符串仅包含空格 var str = "data abc"; if((jQuery.trim( str )).length==0) alert("only spaces"); else alert("contains other characters"); 或者,您可以执行返回布尔值而不是数组的 //assuming input is the stri

如何使用javascript确定输入字符串是否只包含空格?

另一篇好文章:

您只需要应用函数并检查字符串的长度。如果修剪后的长度为0-则字符串仅包含空格

var str = "data abc";
if((jQuery.trim( str )).length==0)
  alert("only spaces");
else 
  alert("contains other characters");

或者,您可以执行返回布尔值而不是数组的

//assuming input is the string to test
if(/^\s*$/.test(input)){
    //has spaces
}

最快的解决方案是使用regex原型函数并查找任何不是空格或换行符的字符
\S

if (/\S/.test(str))
{
    // found something other than a space or a line break
}

如果你有一个超长的字符串,它会有很大的不同。

只需使用搜索。这假设
input
是值,而不是输入元素。是的,像
var input=“dfdfdfd”
,我想,从实际输入中获取输入值不是一个大问题。我更喜欢这个解决方案而不是.trim(),因为您正在寻找特定的字符模式,而这正是正则表达式所描述的。读者可能会花更长的时间来理解你使用trim的巧妙技巧。或者只是
!str.trim()
//assuming input is the string to test
if(/^\s*$/.test(input)){
    //has spaces
}
if (/\S/.test(str))
{
    // found something other than a space or a line break
}