Tutorial :jQuery / JavaScript - string replace



Question:

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"> ?


Solution: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.


Solution:2

You can use regular expressions:

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


Solution:3

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!


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »