|
When using JavaScript to pull a value out from a hidden field and display it in a textbox. If the value in the hidden field is encoded(like "chalk & cheese" ), The problem is that when you read value from the hidden field, JavaScript seems to lose the encoding. To escape " and ', how to make the encoding to remain. (Especially for quote marks
" and
') and white space.
The jQuery trick doesn't encode quote marks and in IE it will strip your whitespace.
Based on the escape templatetag in Django, which I guess is heavily used/tested already, I made this function which does what's needed.
It's arguably simpler (and possibly faster) than any of the workarounds for the whitespace-stripping issue - and it encodes quote marks, which is essential if you're going to use the result inside an attribute value for example.
- function htmlEscape(str) {
- return String(str)
- .replace(/&/g, '&')
- .replace(/"/g, '"')
- .replace(/'/g, ''')
- .replace(/</g, '<')
- .replace(/>/g, '>');
- }
- function htmlUnescape(value){
- return String(value)
- .replace(/"/g, '"')
- .replace(/'/g, "'")
- .replace(/</g, '<')
- .replace(/>/g, '>')
- .replace(/&/g, '&');
- }
复制代码 Update 2013-06-17:
In the search for the fastest escaping I have found this implementation of a replaceAll method:
http://dumpsite.com/forum/index.php?topic=4.msg29#msg29
(also referenced here: http://stackoverflow.com/a/6714233/202168)
Some performance results here:
http://jsperf.com/htmlencoderegex/25
It gives identical result string to the builtin replace chains above.
From: stackoverflow
|
|