检测字符串是否包含任何空格 [英] Detect if string contains any spaces
问题描述
如何检测字符串是否包含空格字符?
How do I detect if a string has any whitespace characters?
以下仅检测实际的空格字符。我需要检查任何类型的空格。
The below only detects actual space characters. I need to check for any kind of whitespace.
if(str.indexOf(' ') >= 0){
console.log("contains spaces");
}
推荐答案
你会发现什么字符串中的空格 where ,而不仅仅是单词之间。
What you have will find a space anywhere in the string, not just between words.
如果你想找到任何类型的空格,你可以使用它,它使用正则表达式:
If you want to find any kind of whitespace, you can use this, which uses a regular expression:
if (/\s/.test(str)) {
// It has any kind of whitespace
}
\s
表示任何空格字符(空格,制表符,垂直制表符,换页符,换行符等),并会在字符串中的任何位置找到该字符。
\s
means "any whitespace character" (spaces, tabs, vertical tabs, formfeeds, line breaks, etc.), and will find that character anywhere in the string.
根据MDN , \s
相当于: [\\\\\\\\\\\\\\\\\\\\\\\\\\\\ \\\ \\\ \\\ \\\ \\\ \\\ \\\ \\\ \\\ \\\
\\\
\ u202f \ u205f \ u3000]
。
出于某种原因,我最初将您的问题读作如何查看字符串是否包含仅空格?所以我回答了下面的问题。但正如@CrazyTrain指出的那样,这不是问题所在。我会离开它,以防万一...
For some reason, I originally read your question as "How do I see if a string contains only spaces?" and so I answered with the below. But as @CrazyTrain points out, that's not what the question says. I'll leave it, though, just in case...
如果你的意思是字面意思空格,正则表达式可以做到:
If you mean literally spaces, a regex can do it:
if (/^ *$/.test(str)) {
// It has only spaces, or is empty
}
这说:匹配字符串的开头( ^
)后跟零个或多个空格字符,后跟字符串的结尾( $
)。如果您不想匹配空字符串,请将 *
更改为 +
。
That says: Match the beginning of the string (^
) followed by zero or more space characters followed by the end of the string ($
). Change the *
to a +
if you don't want to match an empty string.
如果您将空格视为一般概念:
If you mean whitespace as a general concept:
if (/^\s*$/.test(str)) {
// It has only whitespace
}
它使用 \s
(空格)而不是空格,但在其他方面是相同的。 (如果您不想匹配空字符串,请再次将 *
更改为 +
。)
That uses \s
(whitespace) rather than the space, but is otherwise the same. (And again, change *
to +
if you don't want to match an empty string.)
这篇关于检测字符串是否包含任何空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!