【问题标题】:get all text variations from string in javascript从javascript中的字符串获取所有文本变体
【发布时间】:2018-06-20 10:11:39
【问题描述】:

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

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

示例:

Here is example

Here is Instance

This is example

...

【问题讨论】:

  • 让问题更清晰

标签: javascript regex string


【解决方案1】:

对这两个选项使用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);

【讨论】:

    【解决方案2】:

    现代 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);

    【讨论】:

    • 如果参数的数量是动态的呢?
    • 那就更复杂了
    猜你喜欢
    • 2018-07-18
    • 1970-01-01
    • 1970-01-01
    • 2022-10-21
    • 1970-01-01
    • 1970-01-01
    • 2016-10-04
    • 2015-08-06
    • 2020-06-16
    相关资源
    最近更新 更多