简体   繁体   中英

How to convert special characters to html?

I currently have this:

var loc = "Stati Uniti d'America"
jQuery('#heading_results h2').text(loc);

The result i got is:

<h2>Stati Uniti d&#039;America</h2>

This is because for other reasons, I am sending via php the string with special characters but i need to convert them back once in the html.

It should come out as

<h2>Stati Uniti d'America</h2>

In order to use & character codes, you must use .html() :

 var loc = "Stati Uniti d&#039;America" jQuery('#heading_results h2').html(loc); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="heading_results"> <h2></h2> </div> 

string htmlspecialchars ( string $string [, int $flags = ENT_COMPAT | ENT_HTML401 [, string $encoding = ini_get("default_charset") [, bool $double_encode = true ]]] )

enter link description here

Rather than using jQuery and dummy html element you can use plain function to convert your text:

 var str = "Stati Uniti d&#039;America"; function decode(text) { return text.replace(/&#([0-9A-Z]{2,3});/g, function (match, numStr) { var num = parseInt(numStr, 10); return String.fromCharCode(num); }); } console.info(decode(str)); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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