JavaScriptでhtml特殊符号を変換するサンプルコード

コード下記
var regSpeChars = [ “^","$","(“,")","[“,"]","{“,"}",".","?","+","*","|","\\"];
var speCharsMap = {“&": “&",
“#":"&#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;"
};
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;
}

JavaScript

Posted by arkgame