为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕森卡 2023-07-06 19:44:58
我正在使用 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,但我想使其基于动态{{ }}如何才能做到这一点?
查看完整描述

1 回答

?
浮云间

TA贡献1829条经验 获得超4个赞

当你使用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) {

  const ans = [];


  const linkTokenRegex = /\{\{.+?\}\}/g;

  const textsArr = str.split(linkTokenRegex);

  const linksArr = str.match(linkTokenRegex);


  textsArr.forEach((textPart, index) => {

    ans.push({

      type: "TEXT",

      content: textPart,

    });

    if (linksArr[index]) {

      ans.push({

        type: "LINK",

        content: linksArr[index],

      });

    }

  });

  return ans;

}


console.log(splitString(source));


查看完整回答
反对 回复 2023-07-06
  • 1 回答
  • 0 关注
  • 102 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信