如何检测一个字符串中是否包含任何空格字符?
下面的代码只能检测实际空格字符。我需要检查任何类型的空格符。
if(str.indexOf(' ') >= 0){
console.log("contains spaces");
}
如何检测一个字符串中是否包含任何空格字符?
下面的代码只能检测实际空格字符。我需要检查任何类型的空格符。
if(str.indexOf(' ') >= 0){
console.log("contains spaces");
}
你要查找的是字符串中的任何空格,而不仅仅是单词之间的空格。
如果你想查找任何类型的空白字符,可以使用正则表达式:
if (/\s/.test(str)) {
// It has any kind of whitespace
}
\s
代表“任何空格字符”(空格、制表符、垂直制表符、换页符、换行符等),并且可以在字符串中的任何位置找到该字符。
根据MDN的说法,\s
等同于:[ \f\n\r\t\v\u00a0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000]
。
由于某种原因,我最初将您的问题解读为“如何查看字符串是否仅包含空格?”因此,我以下面的答案回答了这个问题。但是正如@CrazyTrain指出的那样,这不是问题的要求。但为了保险起见,我还是保留了它...
如果您确实指的是空格,那么可以使用正则表达式:
if (/^ *$/.test(str)) {
// It has only spaces, or is empty
}
^
),后跟零个或多个空格字符,后跟字符串结尾($
)。如果不想匹配空字符串,则将*
更改为+
。if (/^\s*$/.test(str)) {
// It has only whitespace
}
这里使用的是 \s
(空白字符),而不是空格,但其他方面与之相同。(如果您不想匹配空字符串,请将 *
更改为 +
。)
function hasSpaces(str) {
if (str.indexOf(' ') !== -1) {
return true
} else {
return false
}
}
var inValid = new RegExp('^[_A-z0-9]{1,}$');
var value = "test string";
var k = inValid.test(value);
alert(k);
\S
),使用类似以下表达式的方式:^\S+$
function has_any_spaces(regex, str) {
if (regex.test(str) || str === '') {
return false;
}
return true;
}
const expression = /^\S+$/g;
const string = 'foo baz bar';
console.log(has_any_spaces(expression, string));
push
函数:
const regex = /^\S+$/gm;
const str = `
foo
foo baz
bar
foo baz bar
abc
abc abc
abc abc abc
`;
let m, arr = [];
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
// Here, we push those strings without spaces in an array
m.forEach((match, groupIndex) => {
arr.push(match);
});
}
console.log(arr);
jex.im 可视化正则表达式:
var string = 'hello world';
var arr = string.split(''); // converted the string to an array and then checked:
if(arr[i] === ' '){
console.log(i);
}
我知道正则表达式也可以解决这个问题!
console.log(' foo'.indexOf(' ') !== -1)
和console.log(' '.indexOf(' ') !== -1)
都会输出 true。而console.log(''.indexOf(' ') !== -1)
则会输出 false,因为空字符串不包含空格。我不知道你的s
变量中存储了什么,但是indexOf
应该可以正常工作。 - Elias Van Ootegem