前台Javascript转换特殊字符

/**
* 此脚本用来转换特殊字符,如"&"转换成"&"
*/

//在正则表达式中有特殊意义的字符
var regSpecialChars = [ "^","$","(",")","[","]","{","}",".","?","+","*","|","//"];
//HTML特殊字符集的Map
var specialCharsMap = {"&": "&", //必须放在第一个,先将&转换了,之后就不会影响到转换后生成的&
                    "#":"&#35",//必须放在第二个,先将&转换了,之后就不会影响到转换后生成的&
                    ">" : ">",
                    "<" : "&lt;",
                    "‘":"&lsquo",
                    "’":"&rsquo",
                    ",":"&sbquo",
                    "'":"&#39",
                    "//":"&#92;",
                    "/"":"&ldquo;",
                    "!":"&#33",
                    "%":"&#37",
                    "~":"&#126",
                    "@":"&#64",
                    "=":"&#61",
                    "(":"&#40",
                    ")":"&#41",
                    "{":"&#123",
                    "}":"&#125",
                    "[":"&#91;",
                    "]":"&#93;",
                    "$":"&#36",
                    "?":"&#63",
                    "*":"&#42;",
                    "|":"&#124;",
                    "^":"&#94;",
                    ".":"&#46;",
                    "+":"&#43;",
                    "/":"&#47;",
                    " ":"&nbsp;"
                }; //特殊字符Map定义结束


/**将含有特殊字符的字符串进行转换,参数为元素的id */
function changeElementSpecialChars(elementId){
    var element = document.getElementById(elementId);
    var value = changeSpecialChars(element.value);
    element.value = value;
}

/**将含有特殊字符的字符串进行转换,参数为字符串*/
function changeSpecialChars(value) {
    if(value==null || value == "")
        return value;
    for(var key in specialCharsMap){
        var regex = keyToRegex(key);//有key得到相应的正则表达式
        value = value.replace(regex,specialCharsMap[key]);//根据正则表达式来替换相应的内容
    }
    return value;
}

/**对字符进行处理,如果是正则表达式中的特殊字符,则加上转义字符"/"
返回由参数 key 生成的正则表达式对象
*/
function keyToRegex(key){
    if(isRegexSpecialChar(key)){
        key="//"+key;
    }
    var regex = new RegExp(key,"g");
    return regex;
}

/**判断字符是否是正则表达式中的特殊字符*/
function isRegexSpecialChar(character){
    var length = regSpecialChars.length;
    var ch;
    for(var index = 0; index < length; index++ ) {
        ch = regSpecialChars[index];
        if(character == ch) return true;
    }
    return false;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值