Skip to content

Instantly share code, notes, and snippets.

@tobijibu
Created March 23, 2017 05:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tobijibu/9db182dc730e040ea0f3072e8b364475 to your computer and use it in GitHub Desktop.
Save tobijibu/9db182dc730e040ea0f3072e8b364475 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8>
<title></title>
</head>
<body>
<textarea id="noescape" rows="20" cols="60"></textarea>
<textarea id="escape" rows="20" cols="60"></textarea>
<input type="button" id="esc" value="変換">
<script>
class textReplace {
constructor() {
/**
* 変換対象文字指定
*/
this.replaceEntity = [
['(&(?!#*\\w+;)|&amp;|&#38;)', '&#x26;'], // アンパサンド
['(\\"|&quot;|&#34;)', '&#x22;'], // ダブルクォーテーション
['(\\\'|&#39;)', '&#x27;'], // クォーテーション
['(<|&lt;|&#60;)', '&#x3C;'], // 小なり
['(>|&gt;|&#62;)', '&#x3E;'], // 大なり
];
/**
* ボタンにイベント追加
*/
this.bindEvent('esc');
}
/**
* 特殊文字を16進表記に置換
*/
replaceHexSpChar(string) {
let regExp = new Object();
for (const k of Object.keys(this.replaceEntity)) {
regExp = new RegExp(this.replaceEntity[k][0], 'ig');
string = string.replace(regExp, this.replaceEntity[k][1]);
}
return string;
}
htmlEscape() {
let text = document.getElementById('noescape').value;
document.getElementById('escape').value = rep.replaceHexSpChar(text);
}
bindEvent(id) {
document.getElementById(id).addEventListener('click', this.htmlEscape, false);
}
}
let rep = new textReplace();
</script>
</body>
</html>
class textReplace {
constructor() {
/**
* 変換対象文字指定
*/
this.replaceEntity = [
['(&(?!#*\\w+;)|&amp;|&#38;)', '&#x26;'], // アンパサンド
['(\\"|&quot;|&#34;)', '&#x22;'], // ダブルクォーテーション
['(\\\'|&#39;)', '&#x27;'], // クォーテーション
['(<|&lt;|&#60;)', '&#x3C;'], // 小なり
['(>|&gt;|&#62;)', '&#x3E;'], // 大なり
];
/**
* ボタンにイベント追加
*/
this.bindEvent('esc');
}
/**
* 特殊文字を16進表記に置換
*/
replaceHexSpChar(string) {
let regExp = new Object();
for (const k of Object.keys(this.replaceEntity)) {
regExp = new RegExp(this.replaceEntity[k][0], 'ig');
string = string.replace(regExp, this.replaceEntity[k][1]);
}
return string;
}
htmlEscape() {
let text = document.getElementById('noescape').value;
document.getElementById('escape').value = rep.replaceHexSpChar(text);
}
bindEvent(id) {
document.getElementById(id).addEventListener('click', this.htmlEscape, false);
}
}
let rep = new textReplace();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment