簡體   English   中英

如何在 React Native 或 JS 中解碼特殊字符或 HTML 實體?

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

我從后端獲取字符串,其中包含 HTML 個實體。

‘ ’ “ ” 分別是' '

我使用了不同的 function,例如:-

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

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

output 是解析后的字符串,但它無法替換JavaScriptReact Native中的。 任何幫助,將不勝感激。

編輯:-

我實際上是在傳遞這段文字

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

您可以使用此庫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;∆

這個解決方案對我有用

  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