js 造轮子 HtmlSpecialChars 函数把预定义的字符转换为 HTML 实体
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| class HtmlSpecialChars { constructor() { this.myCodeMap = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''', }; } encoded(text) { for (let key in this.myCodeMap) { let value = this.myCodeMap[key]; text = text.replace(new RegExp(key, 'gm'), value); } return text; } decode(text) { for (let key in this.myCodeMap) { let value = this.myCodeMap[key]; text = text.replace(new RegExp(value, 'gm'), key); } return text; } } module.exports = new HtmlSpecialChars();
|