【问题标题】:Find all instances in text and replace all查找文本中的所有实例并全部替换
【发布时间】:2017-01-30 04:53:09
【问题描述】:

我正在尝试创建一个表并替换 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

请帮忙!

【问题讨论】:

标签: jquery html replace replaceall


【解决方案1】:

将正则表达式与全局 g 一起使用

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

【讨论】:

    【解决方案2】:

    差不多了

    试试这个:

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

    你需要使用全局标志。

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

    【讨论】:

      猜你喜欢
      • 2023-01-12
      • 2023-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-05
      • 2021-12-28
      相关资源
      最近更新 更多