【发布时间】:2021-09-20 12:20:26
【问题描述】:
我有一个这样的降价字符串
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);
UPD
我正在尝试mark不仅app而且<mark>app</mark>s,因为这个功能是供用户搜索
【问题讨论】:
-
您应该在 DOM 级别执行此操作,在您已将此 Markdown 呈现为 HTML。
-
const re = new RegExp(`(\\[^\\][]*]\\([^()]*\\))|${word}`, 'gi');然后return result.replace(re, (x,y) => y || `<mark>${x}</mark>`); -
@CBroe 我会尝试,我不会找到更好的解决方案(因为我使用 React)
-
@wiktor-stribiżew 不起作用:(
-
const re = new RegExp(`(\\[[^\\][]*]\\([^()]*\\))|${word}`, 'gi'); return result.replace(re, (x,y) => y || `<mark>${x}</mark>`);有效。[不见了。
标签: javascript regex algorithm replace markdown