编码特殊字符以传入 url 并由 javascript 读取

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25807515/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 21:54:18  来源:igfitidea点击:

Encode special characters to pass in url and read by javascript

javascripthtml

提问by Biribu

I need to pass some parameters in the url and they can have special characters like ", spanish ? or ?, : spaces and accents.

我需要在 url 中传递一些参数,它们可以包含特殊字符,如 "、西班牙语 ? 或 ?、: 空格和重音符号。

What is the propper way to encode them before adding to the url or in case I got in the html like that, read them?

在添加到 url 之前对它们进行编码的正确方法是什么,或者如果我像那样进入 html,阅读它们?

I tried this:

我试过这个:

arrayData[i] = pair[1].replace('+', " ").replace('%22', "\"");

But just get working with + or spaces, not both at the same time or in 2 lines:

但是只需使用 + 或空格,而不是同时或在 2 行中使用:

    arrayData[i] = pair[1].replace('+', " ");
    arrayData[i] = pair[i].replace('%22', "\"");

回答by Manjar

You can try encodeUri Built-in function, for example

您可以尝试 encodeUri 内置函数,例如

encodeURI('co?o funcionó!')

回答by zmii

Previous answer is correct. JavaScript has built in functions for fulfilling this kind of tasks.

之前的答案是正确的。JavaScript 内置了用于完成此类任务的函数。

You can try to investigate these functions in w3schools.com. Here are the links with basic information and live "Try it out" feature:

您可以尝试在 w3schools.com 中调查这些功能。以下是包含基本信息和实时“试用”功能的链接:

  • encodeURI- takes string with your characters and encodes it into plausible for url style ( encoding spaces and non ANSII chars )
  • decodeURI- takes encoded string and decodes it to initial state
  • encodeURI- 使用您的字符获取字符串并将其编码为合理的 url 样式(编码空格和非 ANSII 字符)
  • decodeURI- 获取编码字符串并将其解码为初始状态