0

I have a variable written from PHP into my javascript (using json_encode), that looks a little like this:

mappoints[x]['about'] = 'Administrator: Foo Barlt;br />Telephone: 555-4202<br />Email: bert@hotmail.com<br />Website: www.domain.com'

That I am using for a google maps map point. Using the json_encode seems to be very picky about what characters I can and cannot enter into it, so i am wondering how I can convert those special html characters into real html characters using javascript?

update

The way i am building my variable is:

var description = "<h3 style='margin: 0; padding: 0;'>" + mappoints[x]['name'] + "</h3><b>Director:</b> " + mappoints[x]['director'] + "<br/>" + mappoints[x]['about'];

The HTML in the varaible is all fine, until I add the about index. No function I have attached or tried yet seems to give me proper HTML.

Chud37
  • 4,907
  • 13
  • 64
  • 116

4 Answers4

4

You can use the dom to decode those entities for you.

mappoints[x]['about'] = 'Administrator: Foo Barlt;br /&gt;Telephone: 555-4202&lt;br /&gt;Email: bert@hotmail.com&lt;br /&gt;Website: www.domain.com'
mappoints[x]['about'] = $('<div/>').append(mappoints[x]['about']).text();

http://jsfiddle.net/5FTCX/

Basically when you add the html to the dom it will show the entities as the characters they represent, using .text() you can receive the data back as you'd see it in the browser as text, not html with the entities. If you want back the html you can use .html() e.g..

Musa
  • 96,336
  • 17
  • 118
  • 137
  • If you append to DOM, the chars are interpreted as HTML, so when you use text() you get the string already interpreted. – Fiambre Apr 17 '14 at 13:20
1

Would it be okay with :

return mystring.replace(/&/g, "&amp;").replace(/>/g, "&gt;").replace(/</g, "&lt;").replace(/"/g, "&quot;");

From here : Convert special characters to HTML in Javascript

Community
  • 1
  • 1
maxime1992
  • 22,502
  • 10
  • 80
  • 121
0

Just because @Musa's idea was great but needed some re-interpreting on my side, I wish to post a quick function here, that will handle htmlspecialchars great, based on @Musa's design :

function htmlspecialchars_decode(string) { $('body').append("<span style='display:none;visibility:hidden;' id='tempText'>" + string + "</span>"); var result = $('#tempText').text(); $('#tempText').remove(); return result; };

Arthur
  • 174
  • 1
  • 1
  • 10
-1

try this

decodeURIComponent(str) or `unescape(str)` or `decodeURI(str)`
Chetan Gawai
  • 2,361
  • 1
  • 25
  • 36