代码之家  ›  专栏  ›  技术社区  ›  Alex

jQuery/JavaScript-字符串替换

  •  2
  • Alex  · 技术社区  · 15 年前

    [quote="comment-1"]
    

    在表单提交之前,如何用表单中的实际html内容替换该代码 <div id="comment-1"> ?

    3 回复  |  直到 15 年前
        1
  •  5
  •   user113716    15 年前

    你可以这样做:

    http://jsfiddle.net/5sYFT/1/

    var text = $('textarea').val();
    
    text = text.replace(/\[quote="comment-(\d+)"\]/g, function(str,p1) { return $('#comment-' + p1).text(); });
    
    $('textarea').val(text);
    

    它应该与你给出的格式中的任何带编号的引号匹配。

        2
  •  0
  •   SLaks    15 年前

    可以使用正则表达式:

    text = text.replace(/\[quote="([a-z0-9-]+)"]/gi, 
        function(s, id) { return $('#' + id).text(); }
    );
    
        3
  •  0
  •   skeggse    15 年前

    // Where textarea is the reference to the textarea, as returned by document.getElementById
    var text = textarea.value;
    text = text.replace(/\[quote\="(comment\-1)"\]/g, '<div id="$1">');
    

    在jQuery中:

    // Where textarea is the reference to the textarea, as returned by $()
    var text = textarea.val();
    text = text.replace(/\[quote\="(comment\-1)"\]/, '<div id="$1">');