Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to decode url-encoded string in javascript

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.

like image 845
Michael Schmidt Avatar asked May 20 '13 08:05

Michael Schmidt


People also ask

What is encodeURI and decodeURI in JavaScript?

The encodeURI() function encodes the complete URI including special characters except except (, / ? : @ & = + $ #) characters. The decodeURI() function decodes the URI generated by the encodeURI() function.

What is JavaScript decodeURI?

The decodeURI() function decodes a Uniform Resource Identifier (URI) previously created by encodeURI() or by a similar routine.

How do I decode a string?

So first, write the very first character of the encoded string and remove it from the encoded string then start adding the first character of the encoded string first to the left and then to the right of the decoded string and do this task repeatedly till the encoded string becomes empty.

How do I use encodeURIComponent in JavaScript?

The encodeURIComponent() function encodes a URI by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character (will only be four escape sequences for characters composed of two "surrogate" characters).


2 Answers

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

like image 196
Lepidosteus Avatar answered Oct 03 '22 16:10

Lepidosteus


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))
like image 27
Chukwuemeka Maduekwe Avatar answered Oct 03 '22 16:10

Chukwuemeka Maduekwe