【问题标题】:How to use / parse HTML entities and Unicode characters in a JavaScript string如何在 JavaScript 字符串中使用/解析 HTML 实体和 Unicode 字符
【发布时间】:2020-04-15 21:10:06
【问题描述】:

我想在 JavaScipt 字符串中使用 ‌ °℃,但这不起作用:

const str = `‌   ° ℃`;

如果我使用console.log(str),我希望看到类似的内容(注意‌ 将不可见,  看起来就像一个常规空间):

   ° ℃

我已经看到 this other question 建议的解决方案是将这些实体更改为等效的十六进制,但这是不可能的,因为该字符串来自后端,并且实体已经到位。

【问题讨论】:

  • HTML 实体是 HTML 解析器的语法,而不是 JavaScript。它们是两种完全不同的语言系统。 JavaScript 有自己的语法来表达基本拉丁语集之外的 Unicode 字符。
  • 没错。我创建了这个问题,因为我看到其他一些关于特定字符的类似问题的问题得到了“使用\xXX”之类的答案,但没有解释如何获取该值或如何动态地执行它,因为人们可能需要什么时候例如,使用 API 从 CMS 消费内容。

标签: javascript html unicode encoding html-entities


【解决方案1】:

即使 HTML 实体已经在该字符串中,无论哪种方式,您都需要将它们替换为它们的实际字符或它们的 escape notation 等效字符。

如果它们不在字符串中,一种选择是查找它们:

或者计算它们:

或者,如果您可以从其他地方键入或复制粘贴原始字符,则可以使用 String.prototype.charCodeAt() 获取其十进制 Unicode 代码,它返回给定索引处的 UTF-16 十进制代码单元,以及 Number.prototype.toString() ,使用其radix 参数将该十进制转换为十六进制:

'°'.charCodeAt(0); // 176
'°'.charCodeAt(0).toString(16); // "b0"

然后使用escape notation 用它们的Unicode 代码来表示它们。请注意,根据代码,我们使用\uXXXX\xXX 表示法:

const str = `\u200C \xA0 \xB0 \u2103`;

console.log(str);

console.log(str.split(' ').map(s => `${ s.charCodeAt(0) } = ${ s.charCodeAt(0).toString(16) }`));

在您的情况下,您需要解析该字符串,提取实体并将它们替换为它们所代表的实际字符。

我制作了这个 sn-p,这样您就可以粘贴字符或编写 HTML 实体并获取它们的 Unicode 代码,但这也可以作为如何动态解析这些 HTML 实体的示例:

const sandbox = document.getElementById('sandbox');
const input = document.getElementById('input');
const list = document.getElementById('list');

function parseInput() {
  let text = input.value;
  
  (text.match(/&.+;/ig) || []).forEach(entity => {
    // Insert the HTML entity as HTML in an HTML element:
    sandbox.innerHTML = entity;
    
    // Retrieve the HTML elements innerText to get the parsed entity (the actual character):
    text = text.replace(entity, sandbox.innerText);
  });
  
  list.innerHTML = text.split('').map(char => {
    const dec = char.charCodeAt(0);
    const hex = dec.toString(16).toUpperCase();
    const code = hex.length === 2 ? `\\x${ hex }` : `\\u${ hex }`;
    const link = `0000${ code }`.slice(-Math.min(4, hex.length ));
  
    return `
      <li>
        <div>${ char }</div>
        <div>${ dec }</div>
        <div>${ hex }</div>
        <div><a href="http://www.fileformat.info/info/unicode/char/${ link }">${ code }</a></div>
      </li>
    `;
  }).join('');  
}

input.value = '&zwnj;&nbsp;°℃';

input.oninput = parseInput;

parseInput();
body {
  margin: 0;
  padding: 8px;
  font-family: monospace;
}

#input {
  margin-bottom: 16px;
  border-radius: 2px;
  border: 0;
  padding: 8px;
  font-family: monospace;
  font-size: 16px;
  font-weight: bold;
  box-shadow: 0 0 32px rgba(0, 0, 0, .25);
  width: 100%;
  box-sizing: border-box;
  height: 40px;
  outline: none;
}

#sandbox {
  display: none;
}

#list {
  list-style: none;
  margin: 0; 
  padding: 0;
  border-top: 1px solid #EEE;
}

#list > li {
  display: flex;
  border-bottom: 1px solid #EEE;
}

#list > li > div {
  width: 25%;
  box-sizing: border-box;
  padding: 8px;
}

#list > li > div + div {
  border-left: 1px solid #EEE;
}
<div id="sandbox"></div>

<input type="text" id="input" />

<ul id="list"></ul>

【讨论】:

    猜你喜欢
    • 2014-06-04
    • 2014-02-06
    • 2018-03-24
    • 2015-11-08
    • 1970-01-01
    • 2015-05-09
    • 2017-09-15
    • 2011-04-14
    • 2019-05-12
    相关资源
    最近更新 更多