How Do I Escape Some Html In Javascript?
Solution 1:
This should work for you: http://blog.nickburwell.com/2011/02/escape-html-tags-in-javascript.html
functionescapeHTML( string )
{
var pre = document.createElement('pre');
var text = document.createTextNode( string );
pre.appendChild(text);
return pre.innerHTML;
}
Security Warning
The function doesn't escape single and double quotes, which if used in the wrong context, may still lead to XSS. For example:
var userWebsite = '" onmouseover="alert(\'gotcha\')" "';
var profileLink = '<a href="' + escapeHtml(userWebsite) + '">Bob</a>';
var div = document.getElemenetById('target');
div.innerHtml = profileLink;
// <a href="" onmouseover="alert('gotcha')" "">Bob</a>
Thanks to buffer for pointing out this case. Snippet taken out of this blog post.
Solution 2:
I ended up doing this:
functionescapeHTML(s) {
return s.replace(/&/g, '&')
.replace(/"/g, '"')
.replace(/</g, '<')
.replace(/>/g, '>');
}
Solution 3:
I like @limc's answer for situations where the HTML DOM document is available.
I like @Michele Bosi's and @Paolo's answers for non HTML DOM document environment such as Node.js.
@Michael Bosi's answer can be optimized by removing the need to call replace 4 times with a single invocation of replace combined with a clever replacer function:
functionescape(s) {
let lookup = {
'&': "&",
'"': """,
'\'': "'",
'<': "<",
'>': ">"
};
return s.replace( /[&"'<>]/g, c => lookup[c] );
}
console.log(escape("<b>This is 'some' text.</b>"));
@Paolo's range test can be optimized with a well chosen regex and the for loop can be eliminated by using a replacer function:
functionescape(s) {
return s.replace(
/[^0-9A-Za-z ]/g,
c =>"&#" + c.charCodeAt(0) + ";"
);
}
console.log(escape("<b>This is 'some' text</b>"));
As @Paolo indicated, this strategy will work for more scenarios.
Solution 4:
Try this htmlentities for javascript
functionhtmlEntities(str) {
returnString(str).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
}
Solution 5:
Traditional Escaping
If you're using XHTML, you'll need to use a CDATA
section. You can use these in HTML, too, but HTML isn't as strict.
I split up the string constants so that this code will work inline on XHTML within CDATA blocks. If you are sourcing your JavaScript as separate files, then you don't need to bother with that. Note that if you are using XHTML with inline JavaScript, then you need to enclose your code in a CDATA block, or some of this will not work. You will run into odd, subtle errors.
functionhtmlentities(text) {
var escaped = text.replace(/\]\]>/g, ']]' + '>]]><' + '![CDATA[');
return'<' + '![CDATA[' + escaped + ']]' + '>';
}
DOM Text Node
The "proper" way to escape text is to use the DOM function document.createTextNode
. This doesn't actually escape the text; it just tells the browser to create a text element, which is inherently unparsed. You have to be willing to use the DOM for this method to work, however: that is, you have use methods such as appendChild
, as opposed to the innerHTML
property and similar. This would fill an element with ID an-element
with text, which would not be parsed as (X)HTML:
var textNode = document.createTextNode("<strong>This won't be bold. The tags " +
"will be visible.</strong>");
document.getElementById('an-element').appendChild(textNode);
jQuery DOM Wrapper
jQuery provides a handy wrapper for createTextNode
named text
. It's quite convenient. Here's the same functionality using jQuery:
$('#an-element').text("<strong>This won't be bold. The tags will be " +
"visible.</strong>");
Post a Comment for "How Do I Escape Some Html In Javascript?"