js转码以&#开头的编码
原创 java_world 发表于:2019-12-01 12:08:50
  阅读 :291   收藏   编辑

代码

(function(window){
	window.htmlentities = {
		/**
		 * Converts a string to its html characters completely.
		 *
		 * @param {String} str String with unescaped HTML characters
		 **/
		encode : function(str) {
			var buf = [];
			
			for (var i=str.length-1;i>=0;i--) {
				buf.unshift(['&#', str[i].charCodeAt(), ';'].join(''));
			}
			
			return buf.join('');
		},
		/**
		 * Converts an html characterSet into its original character.
		 *
		 * @param {String} str htmlSet entities
		 **/
		decode : function(str) {
			return str.replace(/&#(\d+);/g, function(match, dec) {
				return String.fromCharCode(dec);
			});
		}
	};})(window);

测试

console.log(htmlentities.encode('中华人民共和国'))
console.log(htmlentities.decode('中华人民共和国'))

输出

中华人民共和国
中华人民共和国