元问答栏目视频美女
  1. 编程问答
  2. 答案列表
  3. 答案正文

Js怎么实现HTML标签转义及反转义

转义中文及html的完整代码。
$package("js.lang");// 没有包管理时,也可简单写成 js = {lang:{}}
js.lang.string = function(){
this.regx_html_encode = /"|&|'|<|>|[\x00-\x20]|[\x7f-\xff]|[\u0100-\u2700]/g
this.regx_html_decode = /&\w+;|&#(\d+);/g
this.regx_trim = /(^\s*)|(\s*$)/g
this.html_decode = {
"&lt;":"<&quot
"&gt;":">&quot
"&amp;":"&&quot
"&nbsp;":"&quot
"&quot;":"\"&quot
"&copy;":"&quot
// add more
}
this.encodehtml = function(s){
s、s!= undefined)?s:this.tostring()。
return (typeof s!= "string")?s
s、replace(this.regx_html_encode
function($0){
var c = $0.charcodeat(0),r = ["&#"]。
c、c == 0x20)?0xa0:c
r、push(c);r.push(";")。
return r.join("")。
})。
}
this.decodehtml = function(s){
var html_decode = this.html_decode
s、s!= undefined)?s:this.tostring()。
return (typeof s!= "string")?s
s、replace(this.regx_html_decode
function($0,$1){
var c = html_decode[$0]。
if(c == undefined){
// maybe is entity number
if(!isnan($1)){
c、string.fromcharcode(($1 == 160)?32:$1)。
}else{
c、0。
}
}
return c
})。
}
this.trim = function(s){
s、s!= undefined)?s:this.tostring()。
return (typeof s!= "string")?s
s、replace(this.regx_trim,"")。
}
this.hashcode = function(){
var hash = this.__hash__,_char
if(hash == undefined || hash == 0){
hash = 0。
for (var i = 0,len=this.length;i <len;i++) {
_char = this.charcodeat(i)。
hash = 31*hash + _char
hash = hash &hash;// convert to 32bit integer
}
hash = hash &0x7fffffff
}
this.__hash__ = hash
return this.__hash__。
}
}
js.lang.string.call(js.lang.string)。
在实际的使用中可以有两种方式。
1)使用js.lang.string.encodehtml(s)和js.lang.string.decodehtml(s)。
2)还可以直接扩展string的prototype
js.lang.string.call(string.prototype)。
// 那么。
var str = "<b>&'\"中国</b>abc def&quot
var ec_str = str.encodehtml()。
document.write(ec_str)。
document.write("<bt><bt>");// cu的博客在线编辑有bug
放不上来。
var dc_str = ec_str.decodehtml()。
document.write(dc_str)。
@yuty评:0
猜你喜欢