1

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?

1
  • 1
    Replace ')|(' in the RegExp declaration with '|'. Commented Mar 17, 2021 at 11:19

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.