35

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.

Lepidosteus
  • 11,779
  • 4
  • 39
  • 51
Michael Schmidt
  • 423
  • 1
  • 4
  • 6
  • That's not "UTF-8 codes". Why is the data encoded this way? – deceze May 20 '13 at 08:15
  • 1
    [What Every Programmer Absolutely, Positively Needs To Know About Encodings And Character Sets To Work With Text](http://kunststube.net/encoding/) – deceze May 20 '13 at 08:36
  • 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. – Michael Schmidt May 20 '13 at 14:07

2 Answers2

59

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

Lepidosteus
  • 11,779
  • 4
  • 39
  • 51
  • 3
    I'm not sure this is a perfect answer. I have a URL-encoded snippet of a URL that decodes with https://www.url-encode-decode.com/ but not via `decodeURIComponent()`: `%40%23%24%%40%23%24%%40%23%24%%40%23%24%%40%23%24%!%40%23%24` – fIwJlxSzApHEZIl Apr 21 '20 at 21:17
  • @fIwJlxSzApHEZIl I'm not sure if your URL encoded snippet is actually correctly encoded. You seem to have tried to encode `@#$%@#$%@#$%@#$%@#$%!@#$`, but that needs to be encoded as `%40%23%24%25%40%23%24%25%40%23%24%25%40%23%24%25%40%23%24%25%21%40%23%24`, not as whatever you have. (whatever encoded yours didn't properly turn `%` into `%25` and `!` into `%21`). – Plagiatus Mar 31 '23 at 08:05
19

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))
Chukwuemeka Maduekwe
  • 6,687
  • 5
  • 44
  • 67