本文介绍了Javascript拆分可以保留拆分值吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 JavaScript 中:

In Javascript :

var myString = "This is my string";

console.log(myString.split(/(\s)/));

输出:["This", " ", "is", " ", "my", " ", "string"]

console.log(myString.split(/\s/));

输出:["This", "is", "my", "string"]

为什么会这样?

推荐答案

您使用的两个正则表达式只是略有不同.

The two regexs you're using are only slightly different.

/(\s)/ 有一个 \s 捕获组,所以当与 split() 一起使用时,它会添加任何东西在捕获组中找到数组.

/(\s)/ has a capture group of \s, so when used with split() it will add the anything found in the capture group to the array.

正则表达式 /\s/ 没有捕获组,所以 split() 忽略匹配并且不将它们添加到数组中.

The regex /\s/ has no capture group, so split() ignores the matches and does not add them to the array.

同样,如果你执行:

var myString = "This is my string";

console.log(myString.split(/(my)/));  //includes matched capture group in results
console.log(myString.split(/my/));  //ignores matches

将输出:

["这是", "我的", "字符串"]
["这是","字符串"]

希望有帮助!

这篇关于Javascript拆分可以保留拆分值吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 15:50
查看更多