从javascript中的字符串获取所有文本变体

时间:2018-06-20 10:11:40

标签: javascript regex string

如何在javascript中获取具有以下结构的字符串的所有变体:

"{Here|This|This Really} is {example|Instance |Illustration }"

示例:

Here is example

Here is Instance

This is example

...

2 个答案:

答案 0 :(得分:0)

对两个选项都使用split('|')并遍历它们以获得所有组合:

var option1 = "Here|This|This Really";
var option2 = "example|Instance |Illustration";
var combination = [];
option1.split('|').forEach((str1) => {
  option2.split('|').forEach((str2) => {
     combination.push(str1 + ' is ' +str2);
  });
});

console.log(combination);

答案 1 :(得分:0)

现代Javascript:

const s = "{Here|This|This Really} is {example|Instance |Illustration }"
const [a, b, c] = s.match(/\{(.+)\}(.+)\{(.+)\}/).slice(1),
    combine = [].concat(...a.split('|').map(d => [...c.split('|').map(e => `${d}${b}${e}`)]));
console.log(combine);