2020-04-29 js特殊常用字符转义

JavaScript043

2020-04-29 js特殊常用字符转义,第1张

js特殊字符转义

点的转义:. ==>\\u002E

美元符号的转义:$ ==>\\u0024

乘方符号的转义:^ ==>\\u005E

左大括号的转义:{ ==>\\u007B

左方括号的转义:[ ==>\\u005B

左圆括号的转义:( ==>\\u0028

竖线的转义:| ==>\\u007C

右方括号转义:] ==>\\u005D

右圆括号的转义:) ==>\\u0029

星号的转义:* ==>\\u002A

加号的转义:+ ==>\\u002B

问号的转义:? ==>\\u003F

反斜杠的转义:\ ==>\\u005C

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) 【正确】

/*1.用浏览器内部转换器实现html编码(转义)*/

    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