Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 548
Dejas Avatar asked Apr 18 '12 19:04

Dejas


People also ask

How do I convert plain text to HTML?

Click on Format Text in the Menu bar. Under the Format Text, you will get an option to toggle between HTML text, plain text, and Rich text. You can choose the HTML option and then send your email.

What is parseHTML in Javascript?

parseHTML uses native methods to convert the string to a set of DOM nodes, which can then be inserted into the document. These methods do render all trailing or leading text (even if that's just whitespace).

How do you make a string in HTML?

The simplest way to do this is to create an element, insert the string into with innerHTML , then return the element. /** * Convert a template string into HTML DOM nodes * @param {String} str The template string * @return {Node} The template HTML */ var stringToHTML = function (str) { var dom = document.

Can we convert HTML to JSON?

From HTML to JSON allows loading the Website URL which has tables converting to JSON. Click on the URL button, Enter URL and Submit. Parsing HTML into JSON supports loading the HTML File to transform to JSON. Click on the Upload button and select File.


2 Answers

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

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

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

like image 175
bhamlin Avatar answered Oct 22 '22 12:10

bhamlin


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();
}
like image 37
Starx Avatar answered Oct 22 '22 11:10

Starx