简体   繁体   English

有没有原生方法可以在javascript中使用HTML转义字符实体?

[英]Is there a native way to HTML escape character entities in javascript?

The Unicode character 𠮵 given by point 134069 , has the HTML escape 𠮵 Unicode字符𠮵由点给出134069 ,拥有HTML逃生𠮵

Is there a (preferably native) way to get the HTML escapes for character entities from Javascript? 是否有一种(最好是本机的)方法来从Javascript获取字符实体的HTML转义?

You can get both the point and hex values of the char like this: 您可以像这样获取char的point和hex值:

var codePoint = '𠮵'.codePointAt(0); //codePoint = 134069
var hexValue = '𠮵'.codePointAt(0).toString(16); //hexValue = 20bb5
var htmlEscape = '&#x' + hexValue + ';'; //htmlEscape = 𠮵

Here is a working example: 这是一个工作示例:

 $('#doIt').click(function() { $('#outputHex').html($('#inputText').val().codePointAt(0).toString(16)); $('#outputString').html('&#x' + $('#inputText').val().codePointAt(0).toString(16) + ';'); $('#outputChar').html('&#x' + $('#inputText').val().codePointAt(0).toString(16) + ';'); }); 
 code { display: block; padding: 4px; background-color: #EFEFEF; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <textarea id="inputText"></textarea> <button id="doIt">do it</button> <h3>result</h3> <code id="outputHex"></code> <code id="outputString"></code> <code id="outputChar"></code> 

One more thing, codePointAt is an ES6 function and isn't supported in older browsers. 还有一点,codePointAt是ES6函数,较旧的浏览器不支持。 In case the browser blocks the code from running here: JSFiddle Example 如果浏览器阻止代码在此处运行: JSFiddle示例

Here is a function that converts all non-ASCII7 characters, and < , > , & to HTML entities: 这是一个将所有非ASCII7字符以及<> &为HTML实体的函数:

 function htmlEntities(s) { return Array.from(s).map(function (c) { return c.codePointAt(0) < 128 && '<&>'.indexOf(c) == -1 ? c : '&#x' + c.codePointAt(0).toString(16) + ';'; }).join(''); } var s = 'This is \\u{20BB5}, a special character & encoded in HTML.'; document.body.innerHTML = htmlEntities(s); 

Be aware that in Javascript strings, extended unicode characters are counted as two characters (for example in length ). 请注意,在Javascript字符串中,扩展的unicode字符被视为两个字符(例如length )。 The ES6 constructs like Array.from , [...s] make sure you get the right chunks. ES6构造如Array.from[...s]确保获得正确的块。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM