【问题标题】:JS Highlighting a part of stringJS突出显示字符串的一部分
【发布时间】: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


【解决方案1】:

您想使用 $& 而不是 $1。

$& 插入匹配的子字符串。

延伸阅读:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_string_as_a_parameter

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.';

let query = 'international of expat';
let res = '';
let reg;
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;">$&</strong>`);
}

console.log(res);

【讨论】:

    猜你喜欢
    • 2011-04-07
    • 1970-01-01
    • 1970-01-01
    • 2016-12-03
    • 2014-10-28
    • 2022-01-01
    • 1970-01-01
    • 2018-09-14
    • 2017-08-01
    相关资源
    最近更新 更多