javascript - 替换除了大括号内的单词
问题描述
我有一个这样的降价字符串,
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
我怎样才能做到这一点?
我用来添加mark
s 的代码:
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
,因为此功能用于用户搜索
解决方案
确保单词之前/之后没有字母数字或某些特定字符(如/
、&
和)可能就足够=
了-
。
此外,您可以使用一个正则表达式来执行此操作,并且不需要回调作为调用的参数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);
推荐阅读
- telegram-bot - 我们可以在一个应用程序中使用两个 MTProto 连接吗?
- html - 在 html5 中使用高度作为百分比
- regex - 如何匹配特定字符串后面的字符?
- c++ - LLVM 错误:MCJIT::runFunction 不支持全功能参数传递
- html - Angular - 在一个 HTML 文件中包含两个相同的 ng-template 和组件(如何参考,而不是复制)
- json - 我厌倦了在颤抖中找出我的产品列表长度。你能帮我找出我的问题吗?
- r - 如何将y轴标签放在2行ggplot上
- python - 当我尝试抓取 Web 数据时会弹出以下错误:模块 'html5lib.treebuilders' 没有属性 '_base'
- delphi - THeaderControl,如何使用 VCL 样式显示 CheckBoxes
- c# - 如何向除当前用户之外的所有用户发送推送通知?