Replace plain-text with html using jQuery

I am trying to write a replacewith function in jQuery that will replace specific html words.

Basically, I'm trying to replace something like [this] with <span class='myclass'> when loading a document. I examined a couple of samples, but a couple of things that I saw, I could not get to work. I'm still learning jQuery, so I hope someone can give me a couple of tips on how to try it.

Thanks, Stephen.

HTML / text:

 [this]hello world![/this]​ 

JavaScript:

 $(document).ready(function() { // Using just replace $("body").text().replace(/[this]/g,'<b>') });​ 

- EDIT -

I made a few changes to the function using the Nir demo below. Here are some more details on what I am doing. I am trying to make a built-in fraction that I already have the appropriate classes and something has not been done. It works well when in html, but when I run the jQuery function, it does not work.

Obviously the tags are being replaced, but my css really doesn't work, as I said.

Here is the HTML link HERE

and heres a link to jsfiddle HERE

 $(document).ready(function() { // Using just replace var text = $('body').text(); $("body").html(text.replace(/\[math\]/g,'<span class="container">').replace(/\[\/math\]/g,'</span>')); var textt = $('body').text(); $("body").html(textt.replace(/\[top\]/g,'<div class="containme">').replace(/\[\/top\]/g,'</div>')); var textl = $('body').text(); $("body").html(textl.replace(/\[line\]/g,'<div class="borderme">&nbsp;</div>')); var textb = $('body').text(); $("body").html(textb.replace(/\[bot\]/g,'<div class="containme2">').replace(/\[\/bot\]/g,'</div>')); });​ 

This html

  <span class="readme">Whats up, here a fraction.&nbsp; <span class="container"> <div class="containme">1</div> <div class="borderme">&nbsp;</div> <div class="containme2">2</div> </span> &nbsp;&nbsp;Hello? Whats up, here a fraction.&nbsp; <span class="container"> <div class="containme">1</div> <div class="borderme">&nbsp;</div> <div class="containme2">2</div> </span> &nbsp;&nbsp;Hello? Whats up, here a fraction.&nbsp; </span> 

to this abbreviated markup

 <span class="readme"> Whats up, here a fraction. [math][top]1[/top][line][bot]2[/bot][/math] </span> 
+7
source share
2 answers

javascript replace () returns a new line, it does not change the original line, so it should be:

 $(document).ready(function() { var content = $("body").text().replace(/\[this\]/g,'<b>') $("body").html(content); });​ 

Note that brackets must be escaped, otherwise it will replace each character in brackets with <b> .

Here is fiddle

+6
source

here is a demo using regex :

 $(document).ready(function() { // Using just replace var text = $('body').text(); $("body").html( text.replace(/\[this\]/g,'<b>').replace(/\[\/this\]/g,'</b>') ); }); 
+2
source

All Articles