Search code examples
jqueryhtmlreplacereplaceall

Find all instances in text and replace all


I am trying to create a table and replace all instances inside the td not just the first one. In this case replace all the "/" inside the td tag and not just the first one.

Here is my code:

HTML

  <table border="1">
      <tr><td class="abc">apple</td></tr>
      <tr><td class="abc">ball</td></tr>
      <tr><td class="abc">cat</td></tr>
      <tr><td class="abc">dog/ss/s</td></tr>
  </table>

jQuery

   $('.abc').each(function() {
    var xyz = $(this).text();
    $(this).text(xyz.replace('/', 'puppy')); 
});

Here is a working example: Fiddle

Please help!


Solution

  • use regex with global g

     $('.abc').each(function() {
       var xyz = $(this).text();
       $(this).text(xyz.replace(/\//g, 'puppy'));
     });