2022-03-03

&#x开头的是什么编码

这叫HTML Entities。
js中的解决方案


<script>
(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("世上最牢固的感情不是\"我爱你\",而是\"我习惯了有你\"。彼此依赖,才是最深的相爱。"));
</script>

输出一堆实体如下,浏览器可以直接解析成汉字。

&#19990;&#19978;&#26368;&#29282;&#22266;&#30340;&#24863;&#24773;&#19981;&#26159;&#34;&#25105;&#29233;&#20320;&#34;&#65292;&#32780;&#26159;&#34;&#25105;&#20064;&#24815;&#20102;&#26377;&#20320;&#34;&#12290;&#24444;&#27492;&#20381;&#36182;&#65292;&#25165;&#26159;&#26368;&#28145;&#30340;&#30456;&#29233;&#12290;

发表回复

Your email address will not be published. Required fields are marked *