输入字符串:"There are some strings in my question."
模式:[ "Th", "er"]
预期输出:
["Th","er", "e", " ", "are", " ", "some", " ", "strings", " ", "in", " ", "my", " ", "question", "."]
答案 0 :(得分:1)
您可以先用一个分隔符分隔,然后用另一分隔符分隔,然后平放:
arr.split("Th")
.map(x => x.split("er"))
.reduce((a, b) => [...a, ...b], []);
答案 1 :(得分:1)
您可以按给定的模式和空白进行拆分,然后将其包括在结果集中。
var string = "There are some strings in my question." ,
result = string
.split(/(th|er|\s+)/i)
.filter(Boolean);
console.log(result);
答案 2 :(得分:0)
\s+
和[.,!?;]
添加到给定模式列表中。 join
和|
组成的数组,并使用RegExp
创建动态正则表达式。 ()
,以在字符串为split
时保留分隔符。 filter
数组中的空字符串
const str = "There are some strings in my question.",
patterns = ["Th", "er"];
patterns.push('\\s+', '[.,!?;]');
const regex = new RegExp(`(${patterns.join('|')})`, 'i')
const splits = str.split(regex).filter(a => a)
console.log(regex)
console.log(splits)