[Fixed] JS Highlighting a part of string

Issue

I have an example text

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

and i need to highlight a search request, for example international of expat and also i need to higlight each word what have less than three length, so in output i should have

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.

I use next thing:

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);

but i’ve got incorrect result, what im missing?

Solution

You want to use $& instead of $1.

$& inserts the matched substring.

Further reading: 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);

Leave a Reply

(*) Required, Your email will not be published