104

I have somewhere on website a specific text, let's say "lollypops", and I want to replace all the occurrences of this string with "marshmellows". The problem is that I don't know where exactly the text is. I know I could do something like:

$(body).html($(body).html().replace('lollypops', 'marshmellows'));

This would probably work, but I need to rewrite as little HTML as I can, so I'm thinking something like:

  1. search for the string
  2. find the closest parent element
  3. rewrite only the closest parent element
  4. replace this even in attributes, but not all, for example replace it in class, but not in src

In example, I would have structure like this

<body>
    <div>
        <div>
            <p>
               <h1>
                 <a>lollypops</a>
               </h1>
            </p>
            <span>lollypops</span>
        </div>
    </div>
    <p>
       <span class="lollypops">Hello, World!</span>
       <img src="/lollypops.jpg" alt="Cool image" />
    </p>
<body>

In this example, every occurrence of "lollypops" would be replaced, only <img src="... would remain the same and the only elements that would actually be manipulated would be <a> and both <span>s.
Does anybody know how to do this?

cypher
  • 6,822
  • 4
  • 31
  • 48
  • There's an excellent well-written plugin for replacing text. [jquery-replacetext-plugin](http://www.benalman.com/projects/jquery-replacetext-plugin/). The plug-in replaces text leaving all tags and attributes untouched. You can also find a nice tutorial for this plug-in at [spotlight-jquery-replacetext](http://net.tutsplus.com/tutorials/javascript-ajax/spotlight-jquery-replacetext/) – Hussein Feb 26 '11 at 00:16

6 Answers6

176

You could do something like this:

$("span, p").each(function() {
    var text = $(this).text();
    text = text.replace("lollypops", "marshmellows");
    $(this).text(text);
});

It will be better to mark all tags with text that needs to be examined with a suitable class name.

Also, this may have performance issues. jQuery or javascript in general aren't really suitable for this kind of operations. You are better off doing it server side.

kgiannakakis
  • 103,016
  • 27
  • 158
  • 194
  • I know, unfortunately I can't do this on server side. Also, the solution you suggested is unsuitable for me, as I don't know where exactly the string will be. It may be in ``, it may be in `

    ` and so on...

    – cypher Feb 25 '11 at 08:58
  • Then you could try $("*"), but I wouldn't recommend it. – kgiannakakis Feb 25 '11 at 09:07
15

You could do something this way:

$(document.body).find('*').each(function() {
    if($(this).hasClass('lollypops')){ //class replacing..many ways to do this :)
        $(this).removeClass('lollypops');
        $(this).addClass('marshmellows');
    }
    var tmp = $(this).children().remove(); //removing and saving children to a tmp obj
    var text = $(this).text(); //getting just current node text
    text = text.replace(/lollypops/g, "marshmellows"); //replacing every lollypops occurence with marshmellows
    $(this).text(text); //setting text
    $(this).append(tmp); //re-append 'foundlings'
});

example: http://jsfiddle.net/steweb/MhQZD/

stecb
  • 14,478
  • 2
  • 50
  • 68
11

You could do something like this:

HTML

<div class="element">
   <span>Hi, I am Murtaza</span>
</div>


jQuery

$(".element span").text(function(index, text) { 
    return text.replace('am', 'am not'); 
});
Murtaza JAFARI
  • 674
  • 7
  • 10
9

Below is the code I used to replace some text, with colored text. It's simple, took the text and replace it within an HTML tag. It works for each words in that class tags.

$('.hightlight').each(function(){
    //highlight_words('going', this);
    var high = 'going';
    high = high.replace(/\W/g, '');
    var str = high.split(" ");
    var text = $(this).text();
    text = text.replace(str, "<span style='color: blue'>"+str+"</span>");
    $(this).html(text);
});
A J
  • 3,970
  • 14
  • 38
  • 53
7
var string ='my string'
var new_string = string.replace('string','new string');
alert(string);
alert(new_string);
Sai
  • 225
  • 3
  • 15
-2

Why you just don't add a class to the string container and then replace the inner text ? Just like in this example.

HTML:

<div>
    <div>
        <p>
           <h1>
             <a class="swapText">lollipops</a>
           </h1>
        </p>
        <span class="swapText">lollipops</span>
    </div>
</div>
<p>
   <span class="lollipops">Hello, World!</span>
   <img src="/lollipops.jpg" alt="Cool image" />
</p>

jQuery:

$(document).ready(function() {
    $('.swapText').text("marshmallows");
});
  • 2
    This is a 4 year old and already answered question, but the problem was that I could not do what you are suggesting. – cypher Nov 06 '15 at 07:51
  • This answer completely ignores the OP's specification: "I want to replace all the occurrences of this string... The problem is that I don't know where exactly the text is." – Luke May 15 '19 at 01:19