我该如何使用 JavaScript 判断一个输入字符串是否只包含空格?
我该如何使用 JavaScript 判断一个输入字符串是否只包含空格?
这是一个好的帖子:JavaScript更快的去除空格
你只需要应用 trim
函数并检查字符串长度。如果修剪后的长度为0,则该字符串仅包含空格。
var str = "data abc";
if((jQuery.trim( str )).length==0)
alert("only spaces");
else
alert("contains other characters");
!str.trim()
- Oriolif (!input.match(/^\s*$/)) {
//your turn...
}
input
是值,而不是输入元素。 - Josephvar input="dfdfd"
这样,我想从实际输入中获取输入值并不是一个大问题。 - Chuck Norris另外,您可以使用test()
方法来返回布尔值而不是数组
//assuming input is the string to test
if(/^\s*$/.test(input)){
//has spaces
}
\S
:if (/\S/.test(str))
{
// found something other than a space or a line break
}
if(!input.match(/^([\s\t\r\n]*)$/)) {
blah.blah();
}