jQuery/JavaScript-字符串替换

jQuery/JavaScript-字符串替换,javascript,jquery,html,string,Javascript,Jquery,Html,String,假设我们有一个注释文本区域,用户可以在其中输入以下代码: [quote="comment-1"] 在表单提交之前,如何将该代码替换为来自的实际html内容?您可以尝试以下方法: 它应该与您提供的格式中的任何编号引号匹配。您可以使用正则表达式: text = text.replace(/\[quote="([a-z0-9-]+)"]/gi, function(s, id) { return $('#' + id).text(); } ); 如果我理解正确,您希望将“[quote=co

假设我们有一个注释文本区域,用户可以在其中输入以下代码:

[quote="comment-1"]

在表单提交之前,如何将该代码替换为来自的实际html内容?

您可以尝试以下方法:


它应该与您提供的格式中的任何编号引号匹配。

您可以使用正则表达式:

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

如果我理解正确,您希望将“[quote=comment-1]”之类的内容替换为

在JavaScript中:

// 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">');
希望这有帮助

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