How to decode url-encoded string in javascript
Asked Answered
H

2

45

I use javascript / jquery to fill dom elements that contain umlauts:

var text1 = "Unser platonisches Internetreich droht in die H%E4nde einer bewaffneten Miliz zu fallen."

$("#quote1 span").html(unescape(text1));

How can I get rid of the url encoding e.g. "H%E4nde" and use "Hände" instead? I tried

<meta charset="utf-8" />

<meta name="http-equiv" content="Content-type: text/html; charset=UTF-8"/>

<script type="text/javascript" src="js/index.js" charset="utf-8"></script>

But none of them seem to work...

Thanks for help.

Hyman answered 20/5, 2013 at 8:13 Comment(3)
That's not "UTF-8 codes". Why is the data encoded this way?Abebi
What Every Programmer Absolutely, Positively Needs To Know About Encodings And Character Sets To Work With TextAbebi
I just want to save text in a string and then send it to an dom element. The only way I found was to put in the escape sequences manually and then use unescape.Hyman
G
72

That is not UTF-8, that is percent encoding also known as url encoding.

You can use decodeURIComponent() to convert it back before displaying it

$("#quote1 span").html(decodeURIComponent(text1));

Gristmill answered 20/5, 2013 at 8:15 Comment(0)
S
24

Use either of the following built in JavaScript function to decode any encoded text. No need for jquery or any other library.

const text1 = "Unser platonisches Internetreich droht in die H%E4nde einer bewaffneten Miliz zu fallen."

console.log(decodeURI(text1))

console.log(decodeURIComponent(text1))

update: In case you're wondering how to encode, decoded text, you can use another built in JavaScript function like so

console.log(encodeURI(text1))

console.log(encodeURIComponent(text1))
Strappado answered 20/10, 2020 at 7:35 Comment(1)
This answer can be improved by sharing the conditions under which one might want to use one decoder over the other.Irvingirwin

© 2022 - 2024 — McMap. All rights reserved.