-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 !

1

2 Answers 2

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;
}
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.