Простите, с данными в таком формате как обрезать строку по заданным правилам

Простите, с данными в таком формате как обрезать строку по заданным правилам

данные:

как разрезать струну по заданным правилам

      {
         'content': 'key1vip has been serving you for 2 days, and the customer service will provide you with professional answers and formulate solutions',
         'keywords': [{
           'keyword': 'key1',
           'replaceKeyword': 'On',
           'link': '',
           'color': '',
         }, {
           'keyword': 'key2',
           'replaceKeyword': '30',
           'link': '',
           'color': '',
         }]
       }

Преобразовать в следующий формат

      const _array = [
  {text: 'Already for you'},
  {text: 'on', link: '', color: ''},
  {text: 'vip service'},
  {text: '30', link: '', color: ''},
  {text: 'days, customer service will provide you with professional answers and make plans'},
]

1 ответ

Следующий метод действителен для вашего текущего формата данных. Вам нужно отлаживать другие форматы.

      function transformText(text, keywords) {
  const indexes = keywords.reduce((res, v, i) => (res[v.keyword] = i, res), {})
  const kwReg = RegExp(keywords.map(v => v.keyword).join('|'), 'g');
  const res = [];
  var index = 0;
  text.replace(kwReg, (match, offset) => {
    const kw = keywords[indexes[match]]
    res.push(
      {text: text.slice(index, offset)},
      {text: kw.replaceKeyword, link: kw.link, color: kw.color}
    )
    index = offset+match.length
    return ''
  })
  if(index<text.length) res.push({text: text.slice(index)})
  return res
}

var data = {
         'content': 'key1vip has been serving you for 2 days, and the customer service will provide you with professional answers and formulate solutions',
         'keywords': [{
           'keyword': 'key1',
           'replaceKeyword': 'On',
           'link': 'baidu.com',
           'color': 'red',
         }, {
           'keyword': 'key2',
           'replaceKeyword': '30',
           'link': 'bing.com',
           'color': 'blue',
         }]
       }

transformText(data.content, data.keywords)
Другие вопросы по тегам