0

I have a string (i.e If you ask the makers of paper products, they will tell you that to be Agile you need to write ...) and the search terms (i.e ['makers', 'to be Agile']).

I expect this result If you ask the <strong>makers</strong> of paper products, they will tell you that <strong>to</strong> <strong>be</strong> <strong>Agile</strong> you need to write ...

I implement that with this method but sometimes doesn't work correctly.

private emphasize(text: string, highlights: string[]) {
    return highlights
      .filter(highlight => text.includes(highlight))
      .map(highlight => highlight.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'))
      .reduce((txt, highlight) => {
        return txt.replace(new RegExp(highlight, 'gi'), '<strong>$&</strong>');
      }, text);
  }

1 Answer 1

1

Create a RegExp by joining the highlights with the pipe | symbol, and wrapping with word boundaries (\b). Now use String.replace() to wrap found strings with <strong>. This will wrap entire expressions (to be Agile) with <strong>.

function emphasize(text, highlights) {
  const pattern = new RegExp(`\\b${highlights.join('|')}\\b`, 'gi');

  return text.replace(pattern, '<strong>$&</strong>');
}

const text = 'If you ask the makers of paper products, they will tell you that to be Agile you need to write';
const highlights = ['makers', 'to be Agile'];

const result = emphasize(text, highlights);

console.log(result);

If you really want single words, join the highlights with spaces, then split by spaces and join again with the pipe symbol:

function emphasize(text, highlights) {
  const pattern = new RegExp(`\\b${highlights.join(' ').split(' ').join('|')}\\b`, 'gi');

  return text.replace(pattern, '<strong>$&</strong>');
}

const text = 'If you ask the makers of paper products, they will tell you that to be Agile you need to write';
const highlights = ['makers', 'to be Agile'];

const result = emphasize(text, highlights);

console.log(result);

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

1 Comment

You should warn OP of the caveats related to word boundary usage. It won't work if the keywords start/end with special chars, like ['C++', '.NET code']

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.