April 18, 2012

Is there an easy way to convert text into HTML in JavaScript?

Question by Dejas

Possible Duplicate:
Escaping HTML strings with jQuery
JavaScript/jQuery HTML Encoding

For example, if I wanted to show the user the string x < 3 in HTML I would need to replace the < character with &lt;. Is there a prebuilt function to do this in JavaScript or perhaps jQuery that converts any text string into the corresponding HTML?

Answer by bhamlin

If you want to use jQuery, you can use the text(string) method.

$(".selector").text("x < 5");

http://api.jquery.com/text/

Answer by Starx

Or, Take it simple and do this

var str1 = "x < 3";
str1.replace(/</g, '&lt;');

Here is a function from another question

function htmlEscape(str) {
    return String(str)
            .replace(/&/g, '&amp;')
            .replace(/"/g, '&quot;')
            .replace(/'/g, '&#39;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;');
}

Or, Excellent cheat using jQuery Source

function htmlEncode(value){
  return $('<div/>').text(value).html();
}

function htmlDecode(value){
  return $('<div/>').html(value).text();
}

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!