首页 > 解决方案 > 替换除了大括号内的单词

问题描述

我有一个这样的降价字符串, Status of app [TODO app](url.com/apps/list?appid=q1w2e3) has been changed to completed.
我想用 包装搜索到的单词(请参见下面的函数)<mark></mark>,但跳过链接(url.com/apps/list?appid=q1w2e3),所以我会有TODO <mark>app</mark>但没有url.com/<mark>app</mark>s/list?<mark>app</mark>id=q1w2e3

我怎样才能做到这一点?

我用来添加marks 的代码:

const garbage = /[|\\{}()[\]^$+*?.]/g;

const highlightMarkdown = (originalString = '', highlight = '') => {
  highlight = highlight.trim();
  if (!highlight) return originalString;

  const wordsToFind = highlight.replace(garbage, '').split(' ');

  const result = wordsToFind.reduce((result, word) => {
    const re = new RegExp(`(${word})`, 'gi');

    return result.replace(re, (word) => `<mark>${word}</mark>`);
  }, originalString);

  return result;
};

const result = highlightMarkdown(
  `Status of app [TODO app](url.com/apps/list?appid=q1w2e3) has been changed to completed.`,
  'app'
);

console.log(result);

UPDmark不仅要尝试,app还要尝试<mark>app</mark>s,因为此功能用于用户搜索

标签: javascriptregexalgorithmreplacemarkdown

解决方案


确保单词之前/之后没有字母数字或某些特定字符(如/&和)可能就足够=-

此外,您可以使用一个正则表达式来执行此操作,并且不需要回调作为调用的参数replace。您可以使用反向引用$&

const garbage = /[|\\{}()[\]^$+*?.]/g;

const highlightMarkdown = (originalString = '', highlight = '') => {
  highlight = highlight.trim().replace(garbage, '');
  if (!highlight) return originalString;

  const wordsToFind = highlight.replace(/ /g, '|');
  const re = new RegExp(`(?<![/=&-])\\b(${wordsToFind})\\b(?![/=&-])`, 'gi');
  return originalString.replace(re, '<mark>$&</mark>');
};

const result = highlightMarkdown(
  `Status of app [TODO app](url.com/apps/list?appid=q1w2e3) has been changed to completed.`,
  'app'
);

console.log(result);


推荐阅读