以下代码将someString
拆分为数组,并在separators
var separators = ['\\\.', '\\\(', '\\\)', ':', '\\\?', '\\\!', '\\\"', '\\\n'];
var tokens = someString.split(new RegExp(separators.join('|')));
tokens = tokens.filter(Boolean);
但是,我希望在拆分时保留各自的分隔符。我找到了几个解决方案,但是大多数解决方案只针对一个分隔符,这似乎更容易处理。如何在我的例子中处理多个分隔符,并在拆分时保留它们?
答案 0 :(得分:1)
这个怎么样?
var someString = 'This.Is:A?:Test!With"Delimiters'
var result = someString.split(new RegExp("([" + separators.join("") + "])+"));
现在,您在一个数组中同时拥有元素和分隔符:
console.log(result)
> ["This", ".", "Is", ":", "A", ":", "Test", "!", "With", """, "Delimiters"]
分裂可以这样做:
var elements = [];
var delimeters = [];
for(var i = 0; i < result.length; i=i+2){
elements.push(result[i]);
}
for(var i = 1; i < result.length; i=i+2){
delimeters.push(result[i]);
}
所以你得到:
console.log(elements)
> ["This", "Is", "A", "Test", "With", "Delimeters"]
console.log(delimeters)
> [".", ":", ":", "!", """]
希望它有所帮助!