【发布时间】:2021-06-14 17:24:30
【问题描述】:
我有一个示例文本
const str = 'International of Expat Health Insurance for you and your of family in Ukraine! - Fast & Secure - Free international insurance Callback - Customizable Health plans - Worldwide of Cover. International health Coverage.';
我需要突出显示一个搜索请求,例如international of expat,我还需要突出显示长度小于三个的每个单词,所以在输出中我应该有
International of Expat 为您和您在乌克兰的家人提供健康保险! - 快速和安全 - 免费国际保险回拨 - 可定制的健康计划 - 覆盖全球。 国际健康保险。
我用下一个:
let query = 'international of expat';
let res = '';
let reg: RegExp;
let words = [];
const val = query.replace(/[^\w\s]/gi, '').trim();
if (val.length > 0){
words = val.split(' ');
reg = new RegExp('(?![^<]+>)(' + words.join(' ') + ')|(' + words.filter((x) => x.length > 3).join('|') + ')', 'ig');
res = str.replace(reg, '<strong style="font-weight: bold; color: #1D2533;">$1</strong>');
}
console.log(res);
但我得到了不正确的结果,我错过了什么?
【问题讨论】:
-
将
RegExp声明中的')|('替换为'|'。
标签: javascript angular regex typescript