我正在React中制作一个可以接收特定html页面并在React中转换为页面的App,但是当在< Text>中放置一些字符串时,这些字符没有转换:
—的表示形式是-.
这些字符叫什么?在React中有没有一种方法可以将这些字符转换为相应的文本?
最佳答案
These symbols are called HTML Symbol Entities Many mathematical,
technical,and currency symbols,are not present on a normal keyboard.If no entity name exists,you can use an entity number,a decimal,or
hexadecimal reference.
<Text>
{yourText.replace(/—/gi,'-')}
</Text>
您可以在渲染之前使用this npm模块对文本进行解码:
多个HTML实体的示例
const re = /&[^\s]*;/gi;
const allHtmlEntities = [];
while ((match = re.exec(youtText)) != null) {
const htmlEntity = yourText.substring(match.index,7);
if (allHtmlEntities.indexOf(htmlEntity) === -1) {
allHtmlEntities.push(htmlEntity);
}
}
const entities = new Entities();
for (let i = 0; i < allHtmlEntities.length; i++) {
const decodedValue = entities.decode(allHtmlEntities[i]);
yourText = yourText.replace(new RegExp(allHtmlEntities[i],'g'),decodedValue);
}