htmlEncode : function (html){
//.首先动态创建一个容器标签元素,如DIV
var temp = document.createElement ("div")
//然后将要转换的字符串设置为这个元素的innerText或者textContent
(temp.textContent != undefined ) ? (temp.textContent = html) : (temp.innerText = html)
//最后返回这个元素的innerHTML,即得到经过HTML编码转换的字符串了
var output = temp.innerHTML
temp = null
return output
},
/*2.用浏览器内部转换器实现html解码(反转义)*/
htmlDecode : function (text){
//首先动态创建一个容器标签元素,如DIV
var temp = document.createElement("div")
//.然后将要转换的字符串设置为这个元素的innerHTML(ie,火狐,google都支持)
temp.innerHTML = text
//最后返回这个元素的innerText或者textContent,即得到经过HTML解码的字符串了。 var output = temp.innerText || temp.textContent
temp =null
return output
},
注:这两种方法都是利用innerHTML会编译字符串来实现转义和反转义
/*3.用正则表达式实现html编码(转义)*/
htmlEncodeByRegExp : function (str){
var temp = " "
if(str.length == 0)
return " "
temp = str.replace(/&/g,"&")
temp = temp.replace(//g,">")
temp = temp.replace(/\s/g," ")
temp = temp.replace(/\'/g,"'")
temp = temp.replace(/\"/g,""")
return temp
},
/*4.用正则表达式实现html解码(反转义)*/
htmlDecodeByRegExp:function (str){
var temp = ""
if (str.length == 0)
return " "
temp = str.replace(/&/g,"&")
temp = temp.replace(/</g,"<")
temp = temp.replace(/>/g,">")
temp = temp.replace(/ /g," ")
temp = temp.replace(/'/g,"\'")
temp = temp.replace(/"/g,"\"")
return temp
},
/*5.用正则表达式实现html编码(转义)(另一种写法)*/
html2Escape : function(sHtml) {
return sHtml.replace (/[<>&"]/g,function(c){return{'<':'<','>':'>','&':'&','"':'"'}[c]})
},
/*6.用正则表达式实现html解码(反转义)(另一种写法)*/
escape2Html : function (str) {
var arrEntities = {'lt':'<','gt':'>','nbsp':' ','amp':'&','quot':'"'}
return str.replace(/&(lt|gt|nbsp|amp|quot)/ig,function(all,t){return arrEntities[t]})
}
原文地址: https://www.cnblogs.com/willingtolove/p/11059325.html
场景:从后台请求回来的数据中带有json格式的字符串,需要处理成json对象才能进行操作。JSON.parse(): 使用JSON.parse方法来解析json字符串。 报错: Uncaught SyntaxError: Unexpected token } in JSON at position 30 Uncaught SyntaxError: Unexpected token ' in JSON at position 1 这种报错是由于,json字符串的格式有问题,json字符串中对象的最后一个元素后面不可以再加','逗号了。比如'{ "name": "cxh", "sex": "man",}'使用JSON.parse()就会报错,而且 在json字符串中键值对需要用双引号引起来。 解决方案:使用eval()() 报错:SyntaxError: Unexpected token e in JSON at position 1 由于请求回来的json中带有转义字符,所以才会报这个错误。解决方案:带有转义字符的json字符串使用json json数据使用JSON.parse()有浏览器是不兼容JSON这个对象的,或者有的里面有JSON.parse解析不了的东西,所以暂时还是使用: eval("("+data+")") json源数据字符有转义符应该是必须的,你要看解析出来后是否有多余的转义符json转字符串JSON.stringify总体效果还可以: 前导 0 和小数点报错:SyntaxError: JSON.parse: expected ',' or '}' after property value SyntaxError: JSON.parse: unterminated fractional number Uncaught SyntaxError: Unexpected number in JSON at position 25 Uncaught SyntaxError: Unexpected token } in JSON at position 26 数字不能用 0 开头,比如01,并且你的小数点后面必须跟着至少一个数字。js中的特殊字符,加上转义符\ 。例如:
var txt="We are the so-called "Vikings" from the north." document.write(txt) 【错误】
var txt="We are the so-called \"Vikings\" from the north." document.write(txt) 【正确】