开发者

jquery find and replace

Here is my string.

<div id='content'>here is my text {{ and some more }}</div>

I want to replace all {{ with < pre > tags and }} with < /pre > tags.

so the string would output like this.

<div id='content'>here is my text <pre> and some more </pre></div> 

i need to do this using jquery. i have got so far.

var textarea=$('#content').text();
$(".addesc1").t开发者_StackOverflow中文版ext(textarea).html().replace(/{{/g, "<pre>");

whats the best function to use.


You could do some thing simple like:

var textarea=$('#content'); 
textarea.html(textarea.html().replace("{{","<pre>")).html(textarea.html().replace("}}","</pre>")); 

as illustrated here: http://jsfiddle.net/MarkSchultheiss/psSwE/

This says "Take my jQuery object "textarea" and replace the "{{" and then take that result set and replace the "}}".

I WOULD suggest changing the name of your variable however as "var textarea" just might confuse future developers (make them pause to think is not good).

EDIT: Note that the use of the jQuery "chaining" is one of the cool things about it.


$(".addesc1").text(
    $('#content').text().replace(/{{/g, "<pre>").replace(/}}/g, "</pre>")
);


You are using regex, which is kind of an over kill here.

I suggest :

txt.split('{{').join('<pre>');

Then, using jQuery, you can replace the content of an object like that :

var myobject = $('selector');
myobject.html(myobject.html().split('{{').join('<pre>'));
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜