4
<div id="id1">

   apple

   ball

   dogsss

   dogsssdogsss

   dogsssdogsssdogsss

</div>

How Do I change ALL dogsss to dollsss using jquery?

Here is a code, but how to determine the element?

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

Here is similar question http://stackoverflow.com/questions/8146648/jquery-find-text-and-replace

Tushar
  • 85,780
  • 21
  • 159
  • 179
Arriba
  • 305
  • 2
  • 3
  • 14
  • possible duplicate of [Replace all occurances in javascript](http://stackoverflow.com/questions/13013474/replace-all-occurances-in-javascript) – GillesC Aug 07 '15 at 07:44

5 Answers5

9

Your replace will only remove first occurrence from the string. Use regex with replace to remove all occurrences. Use global flag i.e. g in the regex to replace all occurrences.

Change

$(this).text(text.replace('dog', 'doll')); 

To

$(this).text(text.replace(/dog/g, 'doll')); 

Also, you can use text() with callback to update the innerText of element.

Demo

$('#id1').text(function(i, oldText) {
  return oldText.replace(/dog/g, 'doll');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<div id="id1">

  apple ball dogsss dogsssdogsss dogsssdogsssdogsss

</div>
Tushar
  • 85,780
  • 21
  • 159
  • 179
1

You can use .text with callback, and use regex with /g modifier

$('#id1').text(function(index, text) {
    return text.replace(/dog/g, 'doll'); 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="id1">
   apple
   ball
   dogsss
   dogsss
   dogsss
</div>
Oleksandr T.
  • 76,493
  • 17
  • 173
  • 144
1

Instead of using replace(), use split() and join(), which will replace all occurrences instead of just the first one:

$('#id1').each(function() {
    var text = $(this).text();
    $(this).text(text.split("dog").join("doll")); 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="id1">

   apple

   ball

   dogsss

   dogsss

   dogsss

</div>
Maximillian Laumeister
  • 19,884
  • 8
  • 59
  • 78
1

You should use the '/g' for global in your regular expression. Otherwise only the first match gets replaced.

$(this).text(text.replace(/dog/g, 'doll')); 
LcKjus
  • 121
  • 6
0

That's it:

$('#id1').text(function(index, oldText) {
  return oldText.replace(/dog/g, 'doll');
})

// or not use a function
// $('#id1').text($('#id1').text().replace(/dog/g, 'doll'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="id1">

  apple ball dogsss dogsssdogsss dogsssdogsssdogsss

</div>
iplus26
  • 2,518
  • 15
  • 26