Last active
December 26, 2015 18:19
-
-
Save monjer/7193551 to your computer and use it in GitHub Desktop.
普通版的html前台字符转义与反转义
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| (function(opt_ns , opt_win){ | |
| /** | |
| * @date 2013.10.28 | |
| * reference: | |
| * http://zh.wikipedia.org/wiki/%E6%AD%A3%E5%88%99%E8%A1%A8%E8%BE%BE%E5%BC%8F | |
| * http://www.w3school.com.cn/js/jsref_replace.asp | |
| */ | |
| var escapeMapping = { | |
| '&': '&', | |
| '<': '<', | |
| '>': '>', | |
| '"': '"', | |
| "'": ''' | |
| }; | |
| var unescapeMapping = { | |
| '&': '&', | |
| '<': '<', | |
| '>': '>', | |
| '"': '"', | |
| ''': "'" | |
| }; | |
| var html = { | |
| /** | |
| * html字符转义 | |
| * @param htmlString {String} | |
| * @returns {String} 转义后的普通文本 | |
| */ | |
| escape:function(htmlString){ | |
| if(htmlString){ | |
| return htmlString.toString().replace(/[&<>\"']/g,function(match){ | |
| return escapeMapping[match]; | |
| }); | |
| }else{ | |
| return ""; | |
| } | |
| }, | |
| /** | |
| * 普通文本转义为html文本 | |
| * @param plainText {String} | |
| * @returns {String} 反转义后的html文本 | |
| */ | |
| unescape:function(plainText){ | |
| if(plainText){ | |
| return plainText.toString().replace(/&|<|>|"|'/g,function(match){ | |
| return unescapeMapping[match]; | |
| }); | |
| }else{ | |
| return ""; | |
| } | |
| } | |
| }; | |
| opt_win = opt_win || top ; | |
| opt_ns = opt_ns || opt_win ; | |
| opt_ns.html = html ; | |
| })(); |
monjer
commented
Oct 28, 2013
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment