2

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!

  • 2
    Possible duplicate of [Replacing all occurrences of a string in JavaScript](http://stackoverflow.com/questions/1144783/replacing-all-occurrences-of-a-string-in-javascript) – d.h. Sep 21 '16 at 19:31

2 Answers2

4

use regex with global g

 $('.abc').each(function() {
   var xyz = $(this).text();
   $(this).text(xyz.replace(/\//g, 'puppy'));
 });
BenG
  • 14,826
  • 5
  • 45
  • 60
1

Almost there

try this:

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

You need to use global flag.

Here is the explanation. jQuery - replace all instances of a character in a string

Community
  • 1
  • 1
Anil Pediredla
  • 704
  • 2
  • 8
  • 20