将字符串拆分为数组而不删除分隔符? [英] Split string into array without deleting delimiter?
本文介绍了将字符串拆分为数组而不删除分隔符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个字符串,如
"asdf a b c2 "
我想将它拆分成这样的数组:
And I want to split it into an array like this:
["asdf", " ", "a", " ", " ", "b", " ", "c2", " "]
使用 string.split()
删除空格,结果如下:
Using string.split(" ")
removes the spaces, resulting in this:
["asdf", "a", "", "b", "c2"]
我想插入额外的分隔符,例如
I thought of inserting extra delimiters, e.g.
string.replace(/ /g, "| |").replace(/||/g, "|").split("|");
但这会产生意外结果。
推荐答案
而不是拆分,可能更容易将其视为提取包含分隔符或不分隔符的连续字符的字符串:
Instead of splitting, it might be easier to think of this as extracting strings comprising either the delimiter or consecutive characters that are not the delimiter:
'asdf a b c2 '.match(/\S+|\s/g)
// result: ["asdf", " ", "a", " ", " ", "b", " ", "c2", " "]
'asdf a b. . c2% * '.match(/\S+|\s/g)
// result: ["asdf", " ", "a", " ", " ", "b.", " ", ".", " ", "c2%", " ", "*", " "]
莎士比亚对比赛的更多定义是:
A more Shakespearean definition of the matches would be:
'asdf a b c2 '.match(/ |[^ ]+/g)
到
或(不是
)+。
To or (not to
)+.
这篇关于将字符串拆分为数组而不删除分隔符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文