开发者

Convert tags to html entities

Is it possible to convert html tags to html entities using javascript/jquery using any way possible suc开发者_Python百科h 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.


Try this function for the HTML special characters:

function htmlencode(str) {
    return str.replace(/[&<>"']/g, function($0) {
        return "&" + {"&":"amp", "<":"lt", ">":"gt", '"':"quot", "'":"#39"}[$0] + ";";
    });
}


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.


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 &ampersand (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>


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


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);


var d = "<div>"
d = d.replace(/<|>/g, function(chr){
    return chr == "<" ? "&lt;" : "&gt;"
})
console.log(d)


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, "&lt;").replace(/>/g, "&gt;");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜