Rizwi
Rizwi

Reputation: 117

Replace specific text using jquery

Here is a text in html

...now have strategies to |lead our company| successfully...

and here is what I want using jquery

...now have strategies to <strong>lead our company</strong> successfully...

I tried

jQuery(function(){ 
   jQuery('.quotes').each(function() { 
     console.log(jQuery(this).text()); 
     var text = jQuery(this).text().replace(/[|]/g,"<strong>"); 
     var texts = jQuery(text).replace(/[|]/g,"</strong>");
     jQuery(this).html(text); 
   }); 

});

Upvotes: 2

Views: 139

Answers (1)

Moishe Lipsker
Moishe Lipsker

Reputation: 3034

You can use a regex with a global modifier like this:

\|([^|]+)\|

with a replacement of:

'<strong>$1</strong>'

The | is a special character in regex and can be escaped (\|) to refer to it literally.

The ([^|]+) captures a group containing at least one non | character.

var text = '...now have strategies to |lead our company| successfully...';
text = text.replace(/\|([^|]+)\|/g, '<strong>$1</strong>');
console.log(text);

Upvotes: 2

Related Questions