谁能告诉我为什么我们需要decodeURIComponent

时间:2018-03-15 07:37:31

标签: javascript encodeuricomponent decodeuricomponent

我有这段代码,我无法找到任何解释。当我用Google搜索decodeURIComponent时,它说它与encodeURIComponent相反,但是,我无法在我的代码中的任何地方找到encodeURIComponent。

getParameterByName = (name, url) => {
    if (!url)
       url = window.location.href;
    name = name.replace(/[\[\]]/g, '\\$&');
    const regex = new RegExp(`[?&]${name}(=([^&#]*)|&|#|$)`),
    results = regex.exec(url);
    if (!results)
        return null;
    if (!results[2])
        return '';
    return decodeURIComponent(results[2].replace(/\+/g, ' '));
}

这是网址http://localhost:8000/restaurant.html?id=2

那么,有人可以为我解释这段代码。

1 个答案:

答案 0 :(得分:1)

As defined in the RFC 3986,URI只能包含字符-_.~a-zA-Z0-9:/?#[]@!$&'()*+,;=,其中后者具有一些特殊含义。通过限制这些字符,URL明确分隔(通常通过空格或换行符),并通过代理和其他服务处理非ASCII字符时存在。

如果您填写GET表单,则会对用户输入进行编码。例如,if you google for Hellö Lädies&Gentlemen+Bob,浏览器将请求

https://www.google.com/search?q=Hell%C3%B6+L%C3%A4dies%26Gentlemen%2BBob

您会看到所有非ASCII字符和&符号(&)都已使用百分号和UTF-8 encoding中字符的十六进制表示进行编码。

空格字符的处理方式不同;因为在用户输入中非常共同,所以它被分配了较短的字符+。这意味着+也必须进行百分比编码,%2B

您拥有的代码从URL中提取GET参数name。如果它在那里,最后一行

return decodeURIComponent(results[2].replace(/\+/g, ' '));

首先将空格编码撤消为+

然后使用

decodeURIComponent获取name参数的值。例如,如果用户输入名称René Müller&勒内穆勒,则浏览器将发送name=Ren%C3%A9+M%C3%BCller%26%E5%8B%92%E5%86%85%E7%A9%86%E5%8B%92decodeURIComponent将生成原始输入(try it yourself):

> decodeURIComponent('Ren%C3%A9 M%C3%BCller%26%E5%8B%92%E5%86%85%E7%A9%86%E5%8B%92')
'René Müller&勒内穆勒'
相关问题