[英]Difference between .split(/\s+/) and .split(“ ”)?
:) First of all, sorry my bady english :p I was taking a look to the next js code fragment: :)首先,对不起我的bady english:p我正在查看下一个js代码片段:
var classes = element.className.split(/\s+/);
That code will split the full classname of and element into an array containing every class... but, what's the difference between using .split(/\\s+/)
, and using .split(" ")
? 该代码将完整的类名和元素分成包含每个类的数组......但是,使用
.split(/\\s+/)
和使用.split(" ")
之间有什么区别? i see the same result... 我看到相同的结果......
I tested this with the next simple code in Chrome: 我使用Chrome中的下一个简单代码对此进行了测试:
<!DOCTYPE html>
<html>
<body>
<div id="cono" class="clase1 clase2 clase3-xD">
</div>
<script>
var d = document.getElementById("cono");
console.log(d.className);
var classes = d.className.split(" ");
for (i in classes) {
console.log(classes[i]);
}
</script>
</body>
</html>
I have the same result whether i use .split(" ")
or .split(/\\s+/)
: 无论我使用
.split(" ")
还是.split(/\\s+/)
我都有相同的结果:
clase1 clase2 clase3-xD
clase1 clase2 clase3-xD
clase1
clase1
clase2
clase2
clase3-xD
clase3-XD
Do they have any relevant difference? 他们有任何相关的区别吗?
No, .split(/\\s+/)
, and .split(" ")
are different ones. 不,
.split(/\\s+/)
和.split(" ")
是不同的。 \\s+
matches one or more space characters including line breaks where " "
matches a single horizontal space character. \\s+
匹配一个或多个空格字符,包括换行符,其中" "
匹配单个水平空格字符。 So .split(/\\s+/)
splits the input according to one or more space characters and .split(" ")
splits the input according to a single space. 因此
.split(/\\s+/)
根据一个或多个空格字符拆分输入,而.split(" ")
根据单个空格拆分输入。
Example: 例:
> "foo bar".split(/\s+/)
[ 'foo', 'bar' ]
> "foo bar".split(" ")
[ 'foo', '', '', 'bar' ]
The difference between .split(" ") and .split(/\\s+/) is: .split(“”)和.split(/ \\ s + /)之间的区别是:
The regex " "
正则表达式
" "
The regex /\\s+/
正则表达式
/\\s+/
Short: 短:
" "
splits the array at one single space character. " "
将数组拆分为一个单独的空格字符。
/\\s/
splits the array at every kind of whitespace character /\\s/
在每种空格字符处拆分数组
+
Matches between one and unlimitted times +
一次和无限时间之间的匹配
\\s
captures more types of whitespace than space \\s
捕获比空间更多类型的空白
From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions : 来自https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions :
Matches a single white space character, including space, tab, form feed, line feed. 匹配单个空格字符,包括空格,制表符,换页符,换行符。 Equivalent to
[ \\f\\n\\r\\t\\v\ \ \\ \ \ \ \ \ \ \ \ \ \ \
\
\ \ \ ]
. 相当于
[ \\f\\n\\r\\t\\v\ \ \\ \ \ \ \ \ \ \ \ \ \ \
\
\ \ \ ]
。
Also the +
means it will match on multiple spaces. 此外,
+
表示它将在多个空格上匹配。 So foo bar
will produce a different result: 所以
foo bar
会产生不同的结果:
js> 'foo bar'.split(' ')
["foo", "", "", "", "", "", "bar"]
js> 'foo bar'.split(/\s+/)
["foo", "bar"]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.