JavaScriptでhtml特殊符号を変換するサンプルコード
コード下記
var regSpeChars = [ “^","$","(“,")","[“,"]","{“,"}",".","?","+","*","|","\\"];
var speCharsMap = {“&": “&",
“#":"#″,
“>" : “>",
“<" : “<",
“‘":"&lsquo",
“’":"&rsquo",
“,":"&sbquo",
“'":"'″,
“\\":"\",
“\"":"“",
“!":"!″,
“%":"%″,
“~":"~″,
“@":"@″,
“=":"=″,
“(“:"(",
“)":")″,
“{“:"{",
“}":"}″,
“[“:"[",
“]":"]",
“$":"$″,
“?":"?″,
“*":"*",
“|":"|",
“^":"^",
“.":".",
“+":"+",
“/":"/",
" “:" "
};
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 speCharsMap){
var regex = keyToRegex(key);
value = value.replace(regex,speCharsMap[key]);
}
return value;
}
function keyToRegex(key){
if(isRegexSpecialChar(key)){
key="\\"+key;
}
var regex = new RegExp(key,"g");
return regex;
}
function isRegexSpecialChar(character){
var length = regSpeChars.length;
var ch;
for(var index = 0; index < length; index++ ) {
ch = regSpeChars[index];
if(character == ch) return true;
}
return false;
}