0

I'm using javascript to get some asp.net server variables to display them, problem is that if the have some html special character the string isn't being assigned as it's on server and it displays wrong.

For example the string :

`ALBERTO GÓMEZ SÁNCHEZ` 

is displaying like

`ALBERTO GóMEZ SáNCHEZ`

I know I could use a Replace function but doing that for every possible special html character seems too time consuming... I guess there must be some built-in function that solves that easily but I cannot find it or an easier method than trying to replace every possible html special character.

Do you know any way? Thanks for your help.

jmgross
  • 2,306
  • 1
  • 20
  • 24
user2638180
  • 1,013
  • 16
  • 37

1 Answers1

0

If you want to decode html string use this way:

function decodeHTMLEntities (str) {
    if(str && typeof str === 'string') {
      // strip script/html tags
      str = str.replace(/<script[^>]*>([\S\s]*?)<\/script>/gmi, '');
      str = str.replace(/<\/?\w(?:[^"'>]|"[^"]*"|'[^']*')*>/gmi, '');
      element.innerHTML = str;
      str = element.textContent;
      element.textContent = '';
    }

    return str;
  }

Taken from here: HTML Entity Decode

If you want do put this html string into your DOM, you don't need to decode it, the browser will do this job for you. Just insert it like this:

$("body").html(encodedHtmlStringFromServer);
Community
  • 1
  • 1
freethinker
  • 2,257
  • 4
  • 26
  • 49