replace plain-text with html using jQuery

xxstevenxo picture xxstevenxo · Jul 3, 2012 · Viewed 11.6k times · Source

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

Basically I'm trying to replace something like [this] with <span class='myclass'> as the document is loaded. I've looked around for a couple samples but the couple things I saw I was unable to get to work. I'm still learning jQuery so I'm hoping someone could give me a couple suggestions as what to try.

Thanks in advance, Steven.

HTML/text:

[this]hello world![/this]​

JavaScript:

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

--EDIT--

I've made a few changes to the function using Nir's demo below. Heres a few more details about what I'm doing. I'm trying to make an inline fraction, which I already have the the appropriate classes and whatnot made. It works well when in html, but when I run the jQuery function It doesn't seem to work.

It's obvious the tags are replaced, but my css doesnt really seem to be working as I mentioned.

Heres a link to the HTML HERE

and heres a link to the 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's 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's 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's a fraction.&nbsp;
  </span>

to this shortend markup

<span class="readme"> Whats up, here's a fraction. [math][top]1[/top][line][bot]2[/bot][/math] </span>

Answer

adeneo picture adeneo · Jul 3, 2012

javascript replace() returns a new string, it does not alter the original string, so it should probably be:

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

Notice that the brackets will have to be escaped, otherwise it will replace each character inside the brackets with <b>.

Here's a FIDDLE