我需要一个(javascript兼容的)正则表达式,它将匹配除包含空格的字符串之外的任何字符串。例:
" " (one space) => doesn't match
" " (multiple adjacent spaces) => doesn't match
"foo" (no whitespace) => matches
"foo bar" (whitespace between non-whitespace) => matches
"foo " (trailing whitespace) => matches
" foo" (leading whitespace) => matches
" foo " (leading and trailing whitespace) => matches
答案 0 :(得分:21)
这会查找至少一个非空白字符。
/\S/.test(" "); // false
/\S/.test(" "); // false
/\S/.test(""); // false
/\S/.test("foo"); // true
/\S/.test("foo bar"); // true
/\S/.test("foo "); // true
/\S/.test(" foo"); // true
/\S/.test(" foo "); // true
我想我假设一个空字符串应该只考虑空格。
如果空字符串(技术上不包含所有空格,因为它不包含任何内容)应该通过测试,然后将其更改为...
/\S|^$/.test(" "); // false
/\S|^$/.test(""); // true
/\S|^$/.test(" foo "); // true
答案 1 :(得分:1)
/^\s*\S+(\s?\S)*\s*$/
演示:
var regex = /^\s*\S+(\s?\S)*\s*$/;
var cases = [" "," ","foo","foo bar","foo "," foo"," foo "];
for(var i=0,l=cases.length;i<l;i++)
{
if(regex.test(cases[i]))
console.log(cases[i]+' matches');
else
console.log(cases[i]+' doesn\'t match');
}
答案 2 :(得分:1)
试试这个表达式:
/\S+/
\ S表示任何非空白字符。
答案 3 :(得分:0)
if (myStr.replace(/\s+/g,'').length){
// has content
}
if (/\S/.test(myStr)){
// has content
}
答案 4 :(得分:0)
[我不是我]的答案是最好的:
/\S/.test("foo");
或者你可以这样做:
/[^\s]/.test("foo");