Francisco J. Gutierrez

Simple Javascript String replace

If you have ever tried to display code on your site (like I do below), you’ll know that you have to replace all the < and > characters with the HTML character codes or they’ll still get interpreted as regular code. Usually I would do a find and replace inside my text editor. But I figured there’s got to be a better, faster, and reusable way to do it. And there is. Using javascript you can go do a simple replace function.

Step 1
Give your <code> tag an id: <code id=”id-name”>
“id-name” can be whatever you want.

Step 2
Put this bit of Javascript in your page, I put mine right before the closing body tag.


        var str = document.getElementById("id_name").innerHTML;
		str=str.replace(/</g,"&lt;");
		str=str.replace(/>/g,"&gt;");
		document.getElementById("id_name").innerHTML = str;

Try it out in jsFiddle.net

and see my question about this on stackoverflow.com