-2

I'm doing something to convert the HTML Special Chars into UTF-8 Chars. I tried a few things, but nothing worked.

I have to approaches for solving this problem, I have an js object :

let HTMLCharsObject = {
    """: '"',
    "&": "&",
    "€": "€",
    "&lt;": "<"
}

For exemple, in HTML Chars, " is equal to &quot; and I want to convert &quot; to "

But I also have to arrays :

let HTMLArray = [
    "&quot;",
    "&amp;",
    "&euro;",
    "&lt;"
]


let UTF8Array = [
    '"',
    "&",
    "€",
    "<"
]

And here, the elements are in the same order as the HTMLCharsObject but in separate arrays. So, you can use what you want.

And here's the exemple string:

let string = "This is a &quot; test &amp;"

And as result i'm trying to have "This is a " test &"

Thanks !

Drakeee0909
  • 67
  • 1
  • 8
  • Does this answer your question? [How to decode url-encoded string in javascript](https://stackoverflow.com/questions/16645224/how-to-decode-url-encoded-string-in-javascript) – pilchard Aug 09 '21 at 22:10

2 Answers2

1

It is a little hacky to do this in JavaScript, just use one of these methods

HTML Entity Decode

The easiest way without using frameworks

http://jsfiddle.net/k65s3/

function decodeHtml(html) {
    var txt = document.createElement("textarea");
    txt.innerHTML = html;
    return txt.value;
}
METAYOTA
  • 11
  • 2
0

Strictly making use of your provided data:

let HTMLCharsObject = {
    "&quot;": '"',
    "&amp;": "&",
    "&euro;": "€",
    "&lt;": "<"
}

let UTF8Array = [
    '"',
    "&",
    "€",
    "<"
]

let string = "This is a &quot;...&quot; test &amp;"

let result = string;
for (const [escaped, utf8] of Object.entries(HTMLCharsObject)) {
    // If you have String.prototype.replaceAll
    //result = result.replaceAll(escaped, utf8);
    // Otherwise this:
    let newResult = result.replace(escaped, utf8);
    while (newResult !== result) {
        result = newResult;
        newResult = newResult.replace(escaped, utf8);
    }
}
console.log(result);

If you just want to decode URL encoded characters:

decodeURIComponent(string);
Kelvin Schoofs
  • 8,323
  • 1
  • 12
  • 31