js 转义成html,js转义html,反转义

今天同学问echats 的问题,说有乱码,结果我看到调试器里,js已经编译成html实体了,估计是服务器策略把jsp把输入的变量都变成html实体,导致数据在echats里面显示的不是正常汉字,而是一堆XXXX;费劲千辛万苦找到一篇博客解决了这个问题。

连接:http://blog.chinaunix.net/uid-20511797-id-3118652.html

如果单纯解决这个问题可以提取出部分代码:

1 var Tools=:{}};2 Tools=function(){3 this.HTML_DECODE ={4 "<" : "",6 "&" : "&",7 " ": " ",8 """: "\"",9 "?": ""

10

11 //Add more

12 };13 this.REGX_HTML_DECODE = /&\w+;|(\d+);/g;14 this.decodeHtml=function(s){15 var HTML_DECODE = this.HTML_DECODE;16

17 s = (s != undefined) ? s : this.toString();18 return (typeof s != "string") ?s :19 s.replace(this.REGX_HTML_DECODE,20 function($0, $1){21 var c = HTML_DECODE[$0];22 if(c ==undefined){23 //Maybe is Entity Number

24 if(!isNaN($1)){25 c = String.fromCharCode(($1 == 160) ? 32:$1);26 }else{27 c = $0;28 }29 }30 returnc;31 });32 }}33 Tools.call(Tools)

稍作分析一下。首先HTML_DECODE是常规的几个html实体,对应的几个字符串和实体。

REGX_HTML_DECODE是使用正则匹配以  &开头接下来至少一个字母数字下划线然后接一个分号(/&\w+;/)或者  开头接下来至少一个数字然后接一个分号(/(\d+);/)这个可以涵盖所有html实体了

decodeHtml方法中,首先判断传入 s是否合法,如果合法调用replace方法,将正则匹配的两种结果做处理。首先$0匹配到s中的能被匹配到的字符串,然后查看HTML_DECODE中是否有对应的实体字符串,如果有直接返回对应的字符串(30行),如果没有(22行)则判断组匹配(\d+)是不是数字,如果是数字(25行),使用String.fromCharCode方法转成字符,否则返回匹配到的数字(27行)。

###########################################################################################

再给同学使用的时候发现lenend显示不出来了,一调试发现lengend是数组,转义是有问题的,所以修改了一下方法。

1 var Tools={};2 Tools=function(){3 this.HTML_DECODE ={4 "<" : "",6 "&" : "&",7 " ": " ",8 """: "\"",9 "?": ""

10

11 //Add more

12 };13 this.REGX_HTML_DECODE = /&\w+;|(\d+);/g;14 this.decodeHtml=function(s){15 var HTML_DECODE = this.HTML_DECODE;16

17 s = (s != undefined) ? s : this.toString();18 return (typeof s == "string") ?

19 replacecode(s,HTML_DECODE,this.REGX_HTML_DECODE):(Array.isArray(s))?decodeArray(s,HTML_DECODE,this.REGX_HTML_DECODE):s;20 }21

22 functionreplacecode(s,decode,regxde){23 return s.replace(regxde,function($0, $1){24 var c = decode[$0];25 if(c ==undefined){26 //Maybe is Entity Number

27 if(!isNaN($1)){28 c = String.fromCharCode(($1 == 160) ? 32:$1);29 }else{30 c = $0;31 }32 }33 returnc;34 })35 };36

37 functiondecodeArray(arr,decode,regxde){38 return arr.map(function(item){39 returnreplacecode(item,decode,regxde)40 })41 }42

43 }44 Tools.call(Tools)

测试之后可以了。

来源:https://www.cnblogs.com/web-Timer/p/5706960.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值