skip to Main Content

I am trying to find a specific string on a page, lets say I am trying to find the string "ibf". This string can be in any textelement, headline, etc, so it has no specific class to it. There could also be multiple elements on one page that contain the string.

This is some sample text:

"this is ibf text"

It could look something like this above. Now I want to make only the ibf part bold

"this is <b>ibf</b> text"

What can I try for this? I am happy to use JavaScript or jQuery.

2

Answers


  1. "this is ibf text".replace("ibf", "<b>ibf</b>")
    

    In the general case:

    let toFind = "ibf"
    let str = "this is ibf text"
    let replaced = str.replace(new RegExp(toFind, "g"), `<b>${toFind}</b>`)
    
    Login or Signup to reply.
  2. You can simply achieve that using the String.replaceAll() method.

    Live Demo :

    const changedText = document.getElementById('page-content').innerHTML.replaceAll('ibf', '<span style="color:red">ibf</span>');
    
    document.getElementById('page-content').innerHTML = changedText;
    <div id="page-content">
      <h1>Lorem ipsum dolor sit amet, consectetur ibf elit.</h1>
    
      <h3>Lorem ipsum dolor ibf amet, consectetur adipiscing elit.</h3>
    
      <h5>Lorem ibf dolor sit amet, consectetur adipiscing elit.</h5>
    
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. In sit amet lectus mattis, porttitor mi vehicula, ibf nisi. Pellentesque ultrices lorem ibf, sodales tempus mauris ullamcorper nec. Duis ligula erat, rhoncus eget molestie nec, finibus quis purus. Quisque est nibh, varius ut leo et, venenatis ibf metus. Donec rhoncus purus neque, ac venenatis erat interdum fermentum. Nulla venenatis magna at cursus condimentum. Ibf sed lectus ex.</p>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search