如何在javascript中将字符串拆分成多个模式?

时间:2019-04-23 10:16:33

标签: javascript

输入字符串:"There are some strings in my question."

模式:[ "Th", "er"]

预期输出:

["Th","er", "e", " ", "are", " ", "some", " ", "strings", " ", "in", " ", "my", " ", "question", "."]

3 个答案:

答案 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)