设为首页收藏本站

 找回密码
 注册

QQ登录

只需一步,快速开始

查看: 326|回复: 2

HTML-encoding in JavaScript/jQuery

[复制链接]
发表于 2013-10-27 08:07:23 | 显示全部楼层 |阅读模式
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.
  1. function htmlEscape(str) {
  2.     return String(str)
  3.             .replace(/&/g, '&')
  4.             .replace(/"/g, '"')
  5.             .replace(/'/g, ''')
  6.             .replace(/</g, '<')
  7.             .replace(/>/g, '>');
  8. }

  9. function htmlUnescape(value){
  10.     return String(value)
  11.         .replace(/"/g, '"')
  12.         .replace(/'/g, "'")
  13.         .replace(/</g, '<')
  14.         .replace(/>/g, '>')
  15.         .replace(/&/g, '&');
  16. }
复制代码
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
 楼主| 发表于 2013-10-27 08:10:22 | 显示全部楼层
trick there in source code. replace the first parameters for the first block with
  1. function htmlEscape(str) {
  2.     return String(str)
  3.             .replace(/&/g, '&amp;')
  4.             .replace(/"/g, '&quot;')
  5.             .replace(/'/g, '&#39;')
  6.             .replace(/</g, '&lt;')
  7.             .replace(/>/g, '&gt;');
  8. }

  9. function htmlUnescape(value){
  10.     return String(value)
  11.         .replace(/&quot;/g, '"')
  12.         .replace(/&#39;/g, "'")
  13.         .replace(/&lt;/g, '<')
  14.         .replace(/&gt;/g, '>')
  15.         .replace(/&amp;/g, '&');
  16. }
复制代码



 楼主| 发表于 2013-10-27 08:12:22 | 显示全部楼层
您需要登录后才可以回帖 登录 | 注册

本版积分规则

手机版|小黑屋|BC Morning Website ( Best Deal Inc. 001 )  

GMT-8, 2025-8-25 23:45 , Processed in 0.013275 second(s), 17 queries .

Supported by Best Deal Online X3.5

© 2001-2025 Discuz! Team.

快速回复 返回顶部 返回列表