亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用多個關鍵字動態分割字符串

使用多個關鍵字動態分割字符串

慕森卡 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 關注
  • 128 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號