Cheers,
Brian
/**
* Escapes '"', '&', '<', and '>' so that a string can be safely
included in innerHTML or an HTML
* tag attribute value within double quotes.
* @param {string} str String to escape.
* @returns {string} HTML-escaped string.
*/
gadgets.util.escapeString = function(str) {
return str.replace(/&/g, '&').replace(/</g,
'<').replace(/>/g, '>').replace(/"/g, '"');
};
/**
* Unescapes an HTML-escaped string.
* This is a reverse function of gadgets.util.escapeString.
* @param {string} str String to unescape.
* @param {string} HTML-unescaped string.
*/
gadgets.util.unescapeString = function(str) {
return str.replace(/&([^;]+);/g, function(s, entity) {
switch (entity) {
case 'amp':
return '&';
case 'lt':
return '<';
case 'gt':
return '>';
case 'quot':
return '"';
default:
// Do not process other entities
return s;
}
});
};
Let me see if I read your proposal correctly.
- the return value of escapeString will be safe to use as innerHTML.
- it is not safe as an HTML attribute of any type, href or otherwise.
- it is not safe as a javascript string.
- it is not idempotent.
- escapeString and unescapeString are functional inverses.
Have I understood it properly?
Cheers,
Brian
The only change I think is to escape '&' to '&' and same for
unescape. This has nothing to do w/ security anymore and only to do
with double escaping producing incorrect results (&amp;). Again,
we discussed this a few months ago, and it was decided to NOT escape
'&' for that reason. From security standpoint this is irrelevant, I
personally suggested to escape '&' as it is weird otherwise, but it
was argued that gadget developers will be confused. If it is now
commonly believed that this is OK, go for it (Kevin, didn't I talk to
you about this?)