【问题标题】:Replace n patterns in a string替换字符串中的 n 个模式
【发布时间】:2014-06-06 08:45:26
【问题描述】:

有没有简单的方法来修复这个代码:

title_1 = $(this).closest('tr').find('td').html();
title_2 = $(this).closest('tr').find('td').next().html();
title_3 = $(this).closest('tr').find('td').next().next().html();

question = question.replace(/{title_1}/g, title_1);
question = question.replace(/{title_2}/g, title_2);
question = question.replace(/{title_3}/g, title_3);

所以它不是那么乏味(重复)并且可以涵盖title_模式的n次出现?

我是一个初学者 Javascript 开发人员和一个完整的正则表达式新手(实际上,他们吓到我了!:|),所以我自己无法做到这一点。我尝试在different languages 中为an inspiration 使用look,但失败了。

【问题讨论】:

    标签: javascript regex replace


    【解决方案1】:

    您可以在替换中使用函数,根据您找到的内容获取值:

    question = question.replace(/{title_(\d+)}/g, $.proxy(function(x, m){
      return $(this).closest('tr').find('td:eq('+(m-1)+')').html();
    }, this));
    

    演示:http://jsfiddle.net/n3qrL/

    【讨论】:

    • m 应该是第二个参数。
    • @xdazz:是的,你是对的。感谢您发现这一点。
    【解决方案2】:

    String.prototype.replace() 可以将函数作为第二个参数。

    var $this = $(this);
    question = question.replace(/\{title_(\d+)\}/g, function(match, n) {
      return $this.closest('tr').find('td').eq(n - 1).html();
    });
    

    【讨论】:

      【解决方案3】:

      Demo Here

      试试这个, 泛化为获取所有 td 标签的文本值:

      $("table").find("tr").each(function(){
      
       $(this).find("td").each(function(){
           alert($(this).html());
           var txt=$(this).html();
           //var pattern="/{"+txt+"}/g";
           //question = question.replace(pattern, txt);
       });
      });
      

      注意。在您的问题中,您没有提到 'question' 的价值。请定义“问题”的值

      【讨论】:

      • 是的,你是对的!在 SE 中提问时,我总是被告知只粘贴 重要 部分代码。
      【解决方案4】:

      在我看来,您想获取表格行的前三个单元格的文本内容并使用它来替换字符串的内容,并且 this 是某处的元素行。所以你可以这样做:

      var n = 3;  // number of cells to get the text of
      var textArray = [];
      var tr = $(this).closest('tr')[0];
      var reString;
      
      for (var i=0; i<n; i++) {
        reString = '{title_' + (i+1) + '}';
        question = question.replace(reString, tr.cells[i].textContent);
      }
      

      如果你想避免 jQuery 的 closest,你可以使用一个简单的函数,比如:

      function upTo(el, tagName) {
        tagName = tagName.toLowerCase();
        do {
          el = el.parentNode;
          if (el.tagName && el.tagName.toLowerCase() == tagName) {
            return el;
          }
        } while (el.parentNode)
      }
      

      然后:

      var tr = upTo(this, 'tr');
      

      【讨论】:

      • 是的,你是对的!唯一的区别(如上一个问题的段落中所揭示的)是,我想要一个表格行的 n 单元格,而不是前三个。
      猜你喜欢
      • 1970-01-01
      • 2021-09-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-01
      • 2015-07-07
      • 2021-05-14
      相关资源
      最近更新 更多