简体   繁体   English

如何在 React Native 或 JS 中解码特殊字符或 HTML 实体?

[英]How to decode special character or HTML entities in react native or JS?

I am getting String from backend which has HTML entities.我从后端获取字符串,其中包含 HTML 个实体。

‘ ’ “ ” which are ' ' respectivley.分别是' '

I have used different function such as:-我使用了不同的 function,例如:-

var map = { amp: '&', lt: '<', gt: '>', quot: '"', '#039': "'"};

var output = newsTitle.replace(/&([^;]+);/g, (m, c) => map[c]);

output is the parsed string but it is not able to replace the in JavaScript or React Native . output 是解析后的字符串,但它无法替换JavaScriptReact Native中的。 Any help would be appreciated.任何帮助,将不胜感激。

Edit:-编辑:-

I am actually passing this text in我实际上是在传递这段文字

<Text numberOfLines={2}>
{output}
 </Text>

You can use this library https://github.com/mdevils/node-html-entities 您可以使用此库https://github.com/mdevils/node-html-entities

const Entities = require('html-entities').XmlEntities;

const entities = new Entities();
console.log(entities.decode('&lt;&gt;&quot;&apos;&amp;&copy;&reg;&#8710;')); // <>"'&&copy;&reg;∆

this solution worked for me这个解决方案对我有用

  const decodeHtmlCharCodes = str => {
        const decodedString = document.createElement("textarea");
        decodedString.innerHTML = str;
        return decodedString.value;
    }

 $('form').submit(function() { var theString = $('#string').val(); var varTitle = $('<textarea />').html(theString).text(); $('#output').text(varTitle); return false; }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form action="#" method="post"> <fieldset> <label for="string">Enter a html-encoded string to decode</label> <input type="text" name="string" id="string" /> </fieldset> <fieldset> <input type="submit" value="decode" /> </fieldset> </form> <div id="output"></div> 

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

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