/**
* 此脚本用来转换特殊字符,如"&"转换成"&"
*/
//在正则表达式中有特殊意义的字符
var regSpecialChars = [ "^","$","(",")","[","]","{","}",".","?","+","*","|","//"];
//HTML特殊字符集的Map
var specialCharsMap = {"&": "&", //必须放在第一个,先将&转换了,之后就不会影响到转换后生成的&
"#":"#",//必须放在第二个,先将&转换了,之后就不会影响到转换后生成的&
">" : ">",
"<" : "<",
"‘":"&lsquo",
"’":"&rsquo",
",":"&sbquo",
"'":"'",
"//":"\",
"/"":"“",
"!":"!",
"%":"%",
"~":"~",
"@":"@",
"=":"=",
"(":"(",
")":")",
"{":"{",
"}":"}",
"[":"[",
"]":"]",
"$":"$",
"?":"?",
"*":"*",
"|":"|",
"^":"^",
".":".",
"+":"+",
"/":"/",
" ":" "
}; //特殊字符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;
}
* 此脚本用来转换特殊字符,如"&"转换成"&"
*/
//在正则表达式中有特殊意义的字符
var regSpecialChars = [ "^","$","(",")","[","]","{","}",".","?","+","*","|","//"];
//HTML特殊字符集的Map
var specialCharsMap = {"&": "&", //必须放在第一个,先将&转换了,之后就不会影响到转换后生成的&
"#":"#",//必须放在第二个,先将&转换了,之后就不会影响到转换后生成的&
">" : ">",
"<" : "<",
"‘":"&lsquo",
"’":"&rsquo",
",":"&sbquo",
"'":"'",
"//":"\",
"/"":"“",
"!":"!",
"%":"%",
"~":"~",
"@":"@",
"=":"=",
"(":"(",
")":")",
"{":"{",
"}":"}",
"[":"[",
"]":"]",
"$":"$",
"?":"?",
"*":"*",
"|":"|",
"^":"^",
".":".",
"+":"+",
"/":"/",
" ":" "
}; //特殊字符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;
}