'Native JavaScript support for HTML attribute encoding and JavaScript string encoding?
Attribute values need to be encoded. If I'm building a jQuery object like so:
$('<div data-value="' + value + '">');
Really, value
must be attribute encoded like so:
$('<div data-value="' + HtmlAttributeEncode(value) + '">');
I cannot find such a native function. Some suggest it's simply a matter of replacing double quotes with "
, but Microsoft's HttpEncoder.HtmlAttributeEncode
method encodes these four characters & < " '
. I've seem implementations such as quoteattr
here: https://stackoverflow.com/a/9756789/88409, but that is horribly inefficient, calling replace to iterate over the string multiple times. Likewise, I need a native function for encoding a javascript string (e.g. $('<div onclick="var s =\'' + HtmlAttributeEncode(JavaScriptStringEncode(value)) + '\';alert(s);"></div>).appendTo(body);
<< contrived example for illustration only)
Is there a native equivalent of this functionality?
Note: Please don't mention escape
(which is now deprecated in favor of encodeURI
and encodeURIComponent
) all of which have nothing to do with attribute encoding.
Solution 1:[1]
No.
But you don't need them since you can build elements using DOM methods (or jQuery's wrappers around them) which bypass the need for escaping since you are dealing with a DOM instead of HTML.
$('<div />', { "data-value" : value });
or
var div = document.createElement('div');
div.setAttribute('data-value', value);
If you really want to get the escaped HTML, you can take a DOM and generate HTML from it:
var html = $('<div />').append(
$('<div />', { "data-value" : value })
).html();
Solution 2:[2]
This is quite an old question, but I think more interesting with the javascript templating capabilities:
html = `<table title="${ myTitleVar }"><thead><tr>
</tr></thead></table>`
No longer is this error prone and stringing together hundreds of jquery functions is just impractical and unportable.
So, there is a little trick for encoding attributes. Should work fine. I want to make sure i don't have quotes or some nonsense in myTitleVar
, so:
var $h=$('<span>');
function encodeAttr(t) {
return $h.attr('title',t).attr('title');
}
html = `<table title="${ encodeAttr(myTitleVar) }"><thead><tr>
</tr></thead></table>`
Solution 3:[3]
Found an npm package that will get your job done!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Quentin |
Solution 2 | Garr Godfrey |
Solution 3 | Rannie Aguilar Peralta |