使用多个关键字动态分割字符串

我正在使用 Angular 开发无头 CMS。

在下面的内容中,任何包裹在里面的东西都{{ }}被认为是锚链接。

We processes your data in accordance with the {{policy_placeholder}}. You have the right to object to the processing of your personal data. Check “Your rights” in the {{policy_placeholder}} and {{term_policy}} for more information.;`

所以对于上面的例子,下面是预期的结果

[

  {

    type: "TEXT",

    content: "We processes your data in accordance with the "

  },

  {

    type: "LINK",

    content: "{{policy_placeholder}}"

  },

  {

    type: "TEXT",

    content:

      ". You have the right to object to the processing of your personal data. Check “Your rights” in the "

  },

  {

    type: "LINK",

    content: "{{policy_placeholder}}"

  },

  {

    type: "TEXT",

    content: " and "

  },

  {

    type: "LINK",

    content: "{{terms_placeholder}}"

  },


  {

    type: "TEXT",

    content: " for more information."

  }

];

以下是我尝试过的


splitString = function(string, splitters) {

    var list = [string];

    for(var i=0, len=splitters.length; i<len; i++) {

        traverseList(list, splitters[i], 0);

    }

    const x = flatten(list);

    console.log(x);

    return flatten(list);

}


traverseList = function(list, splitter, index) {

    if(list[index]) {

        if((list.constructor !== String) && (list[index].constructor === String))

            (list[index] != list[index].split(splitter)) ? list[index] = list[index].split(splitter) : null;

        (list[index].constructor === Array) ? traverseList(list[index], splitter, 0) : null;

        (list.constructor === Array) ? traverseList(list, splitter, index+1) : null;    

    }

}


flatten = function(arr) {

    return arr.reduce(function(acc, val) {

        return acc.concat(val.constructor === Array ? flatten(val) : val);

    },[]);

}


var splitList = ["{{policy_placeholder}}", "{{term_policy}}"];

splitString(source, splitList);

问题是我必须手动添加splitList,但我想使其基于动态{{ }}


如何才能做到这一点?


慕森卡
浏览 104回答 1
1回答

浮云间

当你使用spread一个字符串时,你实际上将它分割成字符。const source = `We processes your data in accordance with the {{policy_placeholder1}}. You have the right to object to the processing of your personal data. Check “Your rights” in the {{policy_placeholder2}} for more information.`;function splitString(str) {&nbsp; const ans = [];&nbsp; const linkTokenRegex = /\{\{.+?\}\}/g;&nbsp; const textsArr = str.split(linkTokenRegex);&nbsp; const linksArr = str.match(linkTokenRegex);&nbsp; textsArr.forEach((textPart, index) => {&nbsp; &nbsp; ans.push({&nbsp; &nbsp; &nbsp; type: "TEXT",&nbsp; &nbsp; &nbsp; content: textPart,&nbsp; &nbsp; });&nbsp; &nbsp; if (linksArr[index]) {&nbsp; &nbsp; &nbsp; ans.push({&nbsp; &nbsp; &nbsp; &nbsp; type: "LINK",&nbsp; &nbsp; &nbsp; &nbsp; content: linksArr[index],&nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; }&nbsp; });&nbsp; return ans;}console.log(splitString(source));
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript