rob.m
rob.m

Reputation: 10611

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>

Upvotes: 0

Views: 62

Answers (3)

xxxmatko
xxxmatko

Reputation: 4142

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));

Upvotes: 0

Abdullah Anik
Abdullah Anik

Reputation: 1

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

enter link description here

Upvotes: 0

Neil
Neil

Reputation: 14321

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>

Upvotes: 1

Related Questions