[英]How to split text at white-space while keeping the space?
'foo bar'.split(' ')
> ['foo', 'bar']
'foo bar'.split(' ')
> ['foo', '', '', 'bar']
'foo bar'.split(/\+s/)
> ['foo', 'bar']
Where as what I want is:我想要的是:
'foo bar'.?
> ['foo', ' ', 'bar']
ie I want to split the text at a white space, but I want to capture the whitespace (however long) in the resulting array.即我想在空白处拆分文本,但我想在结果数组中捕获空白(无论多长)。
Use a regular expression, and capture what you are splitting at, by putting it into round brackets:使用正则表达式,并通过将其放入圆括号中来捕获要拆分的内容:
'foo bar'.split(/( )/)
> ['foo', ' ', 'bar']
To capture any amount of any whitespace characters, use the \s
class and the +
quantifier:要捕获任意数量的任意空白字符,请使用
\s
class 和+
量词:
'foo bar'.split(/(\s+)/)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.