开发者

jQuery / JavaScript - string replace

开发者 https://www.devze.com 2023-01-06 11:06 出处:网络
Assuming we hav开发者_如何学Pythone a comment textarea where the user can enter this code: [quote=\"comment-1\"]

Assuming we hav开发者_如何学Pythone a comment textarea where the user can enter this code:

[quote="comment-1"]

How can I replace that code before the form submits with the actual html content from <div id="comment-1"> ?


You could try something like this:

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

It should match agains any numbered quote in the format you gave.


You can use regular expressions:

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


If I understand you correctly, you wish to replace something like '[quote="comment-1"]' with ''.

In 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">');

In 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">');

Hope this helps!

0

精彩评论

暂无评论...
验证码 换一张
取 消