A simple question on the proper usage of _.escape()
Just Learning to use the library.. have the following sample code.
var _escaped = _.escape('let\'s have a party!');
var jsescaped = escape('let\'s have a party!');
var _unescaped = unescape(_escaped);
var jsunescaped = unescape(jsescaped);
console.log (_escaped);
let's have a party!
console.log (jsescaped);
let%27s%20have%20a%20party%21
console.log (_unescaped);
let's have a party!
console.log (jsunescaped);
let's have a party!
How to unescape what is returned from _.escape()?
I can do unescape(escape(...)) to return the same value but having hard time to do the same by
unescape(_.escape(...));
After some amount of google'ing and a kind of understand what happen.. and also find out that underscore.string supports both entity escape and unescape... (escapeHTML and unescapeHTML)... I can use underscore'.string's unescapeHTML function to reverse what underscore escape does ...
Like in below.. So why shouldn't this be added to underscope as well? I've use-case to escape some strings and then unescape that later...
and dont want to bring in other package.. or of course, i can borrow the code from underscope.string but it will be nice if this can be included in underscore. This will make the functionality complete and able to decode what it encode as
(_.unescape(_.escape (...))
//this prints back as "let's have a party!"
console.log (unescapeHTML(_.escape ('let\'s have a party!')));
var escapeChars = {
lt: '<',
gt: '>',
quot: '"',
apos: "'",
amp: '&'
};
function unescapeHTML (str) {
return (''+str).replace(/\&([^;]+);/g, function(entity, entityCode){
var match;
console.log (entity, entityCode);
if (entityCode in escapeChars) {
return escapeChars[entityCode];
} else if (match = entityCode.match(/^#x([\da-fA-F]+)$/)) {
return String.fromCharCode(parseInt(match[1], 16));
} else if (match = entityCode.match(/^#(\d+)$/)) {
return String.fromCharCode(~~match[1]);
} else {
return entity;
}
});
};
The above commit adds an _.unescape function -- although I have a hard time thinking of circumstances where you'd actually want to use it instead of the original data. Give it a spin.