简体   繁体   中英

jQuery / JavaScript - string replace

Assuming we have 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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM