简体   繁体   English

如何在javascript中解码url编码的字符串

[英]How to decode url-encoded string in javascript

I use javascript / jquery to fill dom elements that contain umlauts:我使用 javascript / jquery 来填充包含变音符号的 dom 元素:

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 eg "H%E4nde" and use "Hände" instead?如何摆脱 url 编码,例如“H%E4nde”并改用“Hände”? 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.感谢帮助。

That is not UTF-8, that is percent encoding also known as url encoding.那不是 UTF-8,即百分比编码,也称为 url 编码。

You can use decodeURIComponent() to convert it back before displaying it您可以使用decodeURIComponent()在显示之前将其转换回来

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

Use either of the following built in JavaScript function to decode any encoded text.使用以下任一内置 JavaScript 函数解码任何编码文本。 No need for jquery or any other library.不需要 jquery 或任何其他库。

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更新:如果您想知道如何编码、解码文本,您可以像这样使用另一个内置的 JavaScript 函数

console.log(encodeURI(text1))

console.log(encodeURIComponent(text1))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM