Jquery: Find Text and replace

<div id="id1">
 <p>
   apple
 </p>
 <p>
   ball
 </p>
 <p>
   cat
 </p>
 <p>
   dogsss
 </p>
</div>

How Do I change dogsss to dollsss using jquery?


Solution 1:

You can try

$('#id1 p').each(function() {
    var text = $(this).text();
    $(this).text(text.replace('dog', 'doll')); 
});

http://jsfiddle.net/2EvGF/

You could use instead .html() and/or further sophisticate the .replace() call according to your needs

Solution 2:

$("#id1 p:contains('dog')").html("doll");

that'll do it.

http://jsfiddle.net/pgDFQ/

Solution 3:

try this,

$('#id1').html($('#id1').html().replace('dogsss','dollsss'));

working sample

Solution 4:

Warning string.replace('string','new string') not replaced all character. You have to use regax replace.

For exp: I have a sting old string1, old string2, old string3 and want to replace old to new

Then i used.

    var test = 'old string1, old string2, old string3';

   //***** Wrong method **********
    test = test.replace('old', 'new'); // This  will replaced only first match not all
    Result: new string1, old string2, old string3

  //***** Right method **********
    test = test.replace(/([old])+/g, 'new'); // This  will replaced all match 
    Result: new string1, new string2, new string3

Solution 5:

$('p:contains("dogsss")').text('dollsss');