DEV Community

Cover image for How to bold matching characters in text JavaScript.
Raphael Chaula
Raphael Chaula

Posted on

How to bold matching characters in text JavaScript.

To achieve this, we need to replace a character match with <strong>{input character}</strong> in a particular sentence.

So Here is the function:


const boldMatchCharacters = ({ sentence = "", characters = "" }) => {
    const regEx = new RegExp(characters, 'gi');
    return sentence.replace(regEx, '<strong>$&</strong>')
}

Enter fullscreen mode Exit fullscreen mode
  • I create regex from input characters

  • Using string's replace function, I replace $& which returns the whole match as it is with <strong>$&</strong>

Example
console.log(boldMatchCharacters({ sentence: 'Hello Hello Hello, How are you?', characters: 'hel' }));
Enter fullscreen mode Exit fullscreen mode
Output

<strong>Hel</strong>lo <strong>Hel</strong>lo <strong>Hel</strong>lo, How are you?

Happy Hacking

Top comments (1)

Collapse
 
tyron6397 profile image
anderson alive

Its a good website google to visit more information .