Home > OS >  FInd a specific string and make it bold (use Javascript or jquery)
FInd a specific string and make it bold (use Javascript or jquery)

Time:10-16

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"

Can somebody help me out? Javascript or jQuery can be used for that.

CodePudding user response:

"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>`)

CodePudding user response:

You can simply achieve that with the help of 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>

  • Related