How to wrap part of text with spaces using jQuery?

Here is what i am trying to do

Fox<span>Rox</span>

before

FoxRox

How to wrap around Rox?

+5
source share
2 answers

This will lead to a search of the entire DOM and replace each Roxwith <span>Rox</span>:

$(':contains("Rox")').html(function(index, oldHTML) {
    return oldHTML.replace(/(Rox)/g, '<span>$&</span>');
});​

Live demo

+5
source

In this case, you can use the JavaScript method replace():

'FoxRox'.replace(/(Rox)/, '<span>$1</span>');

To replace this with the entire document, you can try the following:

$(":contains('Rox')").html(function(i,o){
  return o.replace(/(Rox)/g, '<span>$1</span>');
});​

Please note that if your term is not "Rox", you need to change it in the above script.

+5
source

All Articles