How to create a regular expression in typescript to bold trigrams from a search phrase

I am trying to create a regular expression in javascript / typescript to bold search phrases from an array, in this case from an array of trigrams.

An example array looks like this:

const trigrams = ['jon', 'ona', 'nat', 'ath', 'tha', 'han'];

const phrase = 'there is some text here with jonathan in it, and jon, and nat, and than';

My goal:

console.log(phrase);
// prints this:
there is some text here with <b>jonathan</b> in it, and <b>jon</b>, and <b>nat</b>, and <b>than</b>

I would like to bold everything in the phrase that is matched by each array element, but sometimes those letters overlap leaving <b> with in <b> tags.

Here is my code:

let v = phrase;
for (const trigram of trigrams) {

  // split trigram into letters
  const c = trigram.split('');

  // create regex
  const reg = `(<b>)?(\w*${c[0]}\w*)(<\/b>)?(<b>)?(\w*${c[1]}\w*)(<\/b>)?(<b>)?(\w*${c[2]}\w*)(<\/b>)?`;
  let re = new RegExp(reg, 'gi');

  // replace all previous bolds with just one bold
  v = v.replace(re, "<b>$1$3$7</b>");
}
console.log(v);

I can’t wrap my head around this for the moment.

18 thoughts on “How to create a regular expression in typescript to bold trigrams from a search phrase”

Leave a Comment