Skip to content

Instantly share code, notes, and snippets.

@mapiondev
Created June 11, 2010 02:33
Show Gist options
  • Save mapiondev/433961 to your computer and use it in GitHub Desktop.
Save mapiondev/433961 to your computer and use it in GitHub Desktop.
[JavaScript] HTMLエスケープ
/**
* HTMLエスケープ(replace方式)
* @param {String} str 処理対象文字列
* @returns {String} エスケープ済み文字列
* @private
*/
escapeHTML1=function(str){
return str.replace(/&/g,"&")
.replace(/</g,"&lt;")
.replace(/>/g,"&gt;")
.replace(/"/g,"&quot;")
.replace(/'/g,"&#39;")
.replace(/\r\n|\n/g,"<br/>");
};
/**
* HTMLエスケープ(prototype.js方式+replace)
* @param {String} str 処理対象文字列
* @returns {String} エスケープ済み文字列
*/
escapeHTML2=function(str){
if(!MAPION.lang.Snippets.escapeHTML2.div){
MAPION.lang.Snippets.escapeHTML2.div = document.createElement("div");
MAPION.lang.Snippets.escapeHTML2.text = document.createTextNode("");
MAPION.lang.Snippets.escapeHTML2.div.appendChild(MAPION.lang.Snippets.escapeHTML2.text);
};
MAPION.lang.Snippets.escapeHTML2.text.data = str;
return MAPION.lang.Snippets.escapeHTML2.div.innerHTML;
};
/**
* @private
*/
escapeHTML2.div=null;
/**
* HTMLエスケープ、実体はescapeHTML1
* @see escapeHTML1
*/
escapeHTML=escapeHTML1;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment