查找文本中的所有实例并全部替换

Find all instances in text and replace all

我正在尝试创建 table 并 替换 td 内的所有 实例,而不仅仅是第一个实例。在这种情况下,替换 td 标签内的所有“/”,而不仅仅是第一个。

这是我的代码:

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')); 
});

这是一个工作示例:Fiddle

请帮忙!

对全局使用正则表达式 g

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

快到了

试试这个:

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

您需要使用全局标志。

这里是解释。 jQuery - replace all instances of a character in a string