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?
Exampl
In JQuery:
$('<div/>').text('This is fun & stuff').html(); // evaluates to "This is fun & stuff"
http://debuggable.com/posts/encode-html-entities-with-jquery:480f4dd6-13cc-4ce9-8071-4710cbdd56cb
There's a concise way of doing this using String.prototype.replace()
and regular expressions as follows:
var tag = "<h1>This should </h1>be bold<h2> and big</h2>";
var escapedTag = tag.replace(/</g, "<").replace(/>/g, ">");
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);
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.
var d = "<div>"
d = d.replace(/<|>/g, function(chr){
return chr == "<" ? "<" : ">"
})
console.log(d)
I have 2 fast and small implementations for encoding HTML safely.
You can encode all characters in your string:
function encode(e){return e.replace(/[^]/g,function(e){return"&#"+e.charCodeAt(0)+";"})}
Or just target the main characters to worry about (&, inebreaks, <, >, " and ') like:
function encode(r){
return r.replace(/[\x26\x0A\<>'"]/g,function(r){return"&#"+r.charCodeAt(0)+";"})
}
var myString='Encode HTML entities!\n"Safe" escape <script></'+'script> & other tags!';
test.value=encode(myString);
testing.innerHTML=encode(myString);
/*************
* \x26 is &ersand (it has to be first),
* \x0A is newline,
*************/
<p><b>What JavaScript Generated:</b></p>
<textarea id=test rows="3" cols="55"></textarea>
<p><b>What It Renders Too In HTML:</b></p>
<div id="testing">www.WHAK.com</div>