views:

109

answers:

5

Hello,

Is it possible to convert html tags to html entities using javascript/jquery using any way possible such as regex or some other way. If yes, then how?

Example:

<div> should be converted to &lt;div&gt;

Note: I am not talking about server-side languages.

+5  A: 

Try this function for the HTML special characters:

function htmlencode(str) {
    return str.replace(/[&<>"']/g, function($0) {
        return "&" + {"&":"amp", "<":"lt", ">":"gt", '"':"quot", "'":"#39"}[$0] + ";";
    });
}
Gumbo
Why not `apos` instead of `#39`?
Eli Grey
@Eli Grey: The *apos* entity was introduced in XML 1.0 (and thus defined for XHTML) but it is not defined in HTML 4. (See http://www.w3.org/TR/xhtml1/#C_16)
Gumbo
A: 
var d = "<div>"
d = d.replace(/<|>/g, function(chr){
    return chr == "<" ? "&lt;" : "&gt;"
})
console.log(d)
mwilcox
+1  A: 

As you tagged with jquery, a jQuery-powered solution should work for you:

$("<div>").text("<div>bleh</div>whatever").html()

Replace the argument to the text-method with whatever markup you want to escape.

Jörn Zaefferer
+1  A: 

In JQuery:

$('<div/>').text('This is fun & stuff').html(); // evaluates to "This is fun &amp; stuff"

http://debuggable.com/posts/encode-html-entities-with-jquery:480f4dd6-13cc-4ce9-8071-4710cbdd56cb

RioTera
+1  A: 

If you have the variable and you want to insert it on a div, you can call text().

var myVar = "<span><strong>Some vars</strong> Some var extra</span>";
$("div").text(myVar);
metrobalderas