我需要基于动态分隔符拆分一个数组,该分隔符将更改,并将分隔符保留在结果数组中.
考虑下面的例子,我需要:
-
拆分
const match = 'somethingcatsomethingcatsomethingcat'
-
使用分离器
const separator = 'cat'
-
并得到以下数组作为结果:
["something", "cat", "something", "cat", "something", "cat"]
.
我是这么做的:
const separator = 'cat'
const match = 'somethingcatsomethingcatsomethingcat'
const standardSplit = match.split(separator)
console.log(standardSplit)
// >> Array ["something", "something", "something", ""]
const withPureRegex = match.split(/(cat)/)
console.log(withPureRegex)
// >> Array ["something", "cat", "something", "cat", "something", "cat", ""]
// This is what I need, without the last element of an empty string.
// But I need to pass in the separator dynamically.
const regex = new RegExp(`/(${separator})/`, 'gi')
const withStringLiteral = match.split(regex)
console.log(withStringLiteral)
// >> Array ["somethingcatsomethingcatsomethingcat"]
我对正则表达式不在行.我已经读了大约articles篇关于在正则表达式中逃逸的文章,但似乎在RegExp
以内没有必要?我try 了RegExp
的许多变种,但都没有成功.
关于这一点有很多问题,但我发现try 使用动态分隔符的问题很少.我发现的少数几个问题都有使用字符串文字的答案,还有RegExp
个问题,就像我上面的一样.
如果我只需要这样做一次,我会使用非正则表达式方法,比如使用上面的前split
个方法,然后根据需要手动循环插入分隔符.但在这种情况下,我将多次运行此匹配/替换,如果可以避免,则不能增加更多开销.