0

I need to replace a text using javascript and regex. Such that the words borex, edge and rss feeds get replaced with borex, edge and rss feeds. The text appears like this.

<body>
<img src="http://some.web.site/image.jpg" title="borex" />
These words are highlighted: borex, edge, rss feeds while these words are not: bewedge, borexlumina, rss feedssss
</body>

Get replaced with:

<body>
<img src="http://some.web.site/image.jpg" title="borex" />
These words are highlighted: <b>borex</b>, <b>edge</b>, <b>rss feeds</b> while these words are not: bewedge, borexlumina, rss feedssss
</body>

I tried:

var str = document.getElementByTagName("body")
 str.replace(/borex/g,'<b>borex</b>').replace(/edge/g,'<b>edge</b>').replace(/rss feeds/,'<b>rss feeds</b>')

This gets all of them. How do i get only the word that is not part of another word? Any other suggestions are welcome.. Need some help...

Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285
lakshmen
  • 28,346
  • 66
  • 178
  • 276

2 Answers2

5

Use \b to indicate a word boundry:

str.replace(/\b(borex|edge|rss feeds)\b/g, '<b>$1</b>');

Here's the fiddle: http://jsfiddle.net/ELaWZ/

Community
  • 1
  • 1
Joseph Silber
  • 214,931
  • 59
  • 362
  • 292
3

Use regex word boundaries:

str.replace(/\bborex\b/g,'<b>borex</b>').replace(/\bedge\b/g,'<b>edge</b>').replace(/\brss feeds\b/,'<b>rss feeds</b>')
Alex Kalicki
  • 1,533
  • 9
  • 20