如何使用javascript确定输入字符串是否只包含空格?
Another good post for : Faster JavaScript Trim
You just need to apply trim
function and check the length of the string. If the length after trimming is 0 - then the string contains only spaces.
var str = "data abc";
if((jQuery.trim( str )).length==0)
alert("only spaces");
else
alert("contains other characters");
if (!input.match(/^\s*$/)) {
//your turn...
}
Alternatively, you can do a test()
which returns a boolean instead of an array
//assuming input is the string to test
if(/^\s*$/.test(input)){
//has spaces
}
if(!input.match(/^([\s\t\r\n]*)$/)) {
blah.blah();
}
The fastest solution is using the regex prototype function test() and looking for any character that is not a space or a line break \\S
:
if (/\S/.test(str))
{
// found something other than a space or a line break
}
In case that you have a super long string, it can make a significant difference.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.