zoukankan      html  css  js  c++  java
  • 不要再造轮子了:聊一聊 JavaScript 的 URL 对象是什么?

    本文由葡萄城技术团队于博客园翻译并首发

    转载请注明出处:葡萄城官网,葡萄城为开发者提供专业的开发工具、解决方案和服务,赋能开发者。

    如果我们自己编写从URL中分析和提取元素的代码,那么有可能会比较痛苦和麻烦。程序员作为这个社会中最“懒”的群体之一,无休止的重复造轮子必然是令人难以容忍的,所以大多数浏览器的标准库中都已经内置了URL对象。

    那么现在,有了它,我们就可以将URL字符串作为参数传递给URL的构造函数,并创建它的实例解析URL内容了吗?答案是:“是的!”。

    要使用URL构造函数创建URL对象,我们在以下代码中使用new来创建:

    new URL('https://www.grapecity.com.cn');

    在上面的代码中,我们创建了一个绝对地址的URL对象的实例。但同时,我们还可以传入一个相对地址作为第一个参数,并把相对地址的基础URL作为第二个参数来创建一个URL对象。可能比较拗口,我们举个栗子:

    new URL('/developer', 'https://www.grapecity.com.cn');

    看上面的代码,第二个基础URL参数必须是一个有效的绝对地址,而不可以是一个相对的地址片段,它必须要以http://或https://开头,我们还可以在下面的代码中以类似于链式定义的方式来使用:

    const gcUrl = 'https://www.grapecity.com.cn/';
    
    const gcDevUrl = new URL("/developer", gcUrl);
    
    const gcUrl2 = new URL(gcUrl);
    
    const gcSlnUrl = new URL('/solutions', gcUrl2);
    
    const Url = new URL('aboutus', gcSlnUrl);

    如果每个参数使用toString()的话,我们的执行结果应该如下:

    https://www.grapecity.com.cn/

    https://www.grapecity.com.cn/developer

    https://www.grapecity.com.cn/

    https://www.grapecity.com.cn/solutions

    https://www.grapecity.com.cn/aboutus

    第二个参数是可选参数,只有当第一个参数是相对地址时才应传入。我们传入的字符串或URL对象被转换为USVString对象,该对象对应于一组Unicode标量值可能的序列集合。在我们的代码中,我们可以将它们视为常规字符串。如果两个参数都是相对地址,或者基础URL和相对地址一起无效,则会抛出TypeError异常。我们可以直接将URL对象传递给第二个参数,因为URL对象的toString方法将在构造函数中操作之前将URL对象转换为完整的URL字符串。

    URL对象可以具有以下属性:

    Hash,host,hostname,href,origin,username/password,pathname,port,protocol,search等属性,接下来,让我们一起来了解一下它们吧!

    Hash属性

    hash属性能获得URL中位于#号后的部分。由于字符串没有经过百分比解码,因此仍然对如下所示的特殊符号进行编码。它们使用下面的映射进行编码。在编码过程中,左侧的字符将转换为右侧的字符:

    • ‘:’ — %3A
    • ‘/’ — %2F
    • ‘?’ — %3F
    • ‘#’ — %23
    • ‘[‘ — %5B
    • ‘]’ — %5D
    • ‘@’ — %40
    • ‘!’ — %21
    • ‘$’ — %24
    • “‘“ — %27
    • ‘(‘ — %28
    • ‘)’ — %29
    • ‘*’ — %2A
    • ‘+’ — %2B
    • ‘,’ — %2C
    • ‘;’ — %3B
    • ‘=’ — %3D
    • ‘%’ — %25
    • ‘ ‘ — %20 或者 +

    例如,我们有这样的URL字符串,https://www.grapecity.com.cn/developer/spreadjs#price,然后我们可以直接取出Hash属性值,如下所示:

    const exampleUrl = new URL('https://www.grapecity.com.cn/developer/spreadjs#price');
    console.log(exampleUrl.hash);

    在运行结果中,我们在console.log语句中得到‘#price’。该属性是一个USVString,当我们像上面那样获取它时,它会被转换为字符串。因为它不是只读属性,所以我们也可以像下面的代码中那样直接为它赋值:

    exampleUrl.hash = '#newHash';

    例如:

    const exampleUrl = new URL('https://www.grapecity.com.cn/developer/spreadjs#price'); 
    exampleUrl.hash ='#newPrice'; 
    console.log(exampleUrl.hash);

    我们通过href属性就能获得更新后的URL https://www.grapecity.com.cn/developer/spreadjs#newHash

    Host 属性

    URL对象的host属性是包含主机名的USVString。如果端口包含在: 之后,则我们还将获得主机的端口号。例如,如果我们有:

    const exampleUrl = new URL('http://huozige.grapecity.com.cn:8080/');
    console.log(exampleUrl.host);

    我们就能获得huozige.grapecity.com.cn:8080。与其他USVString属性一样,当我们检索它时,它会转换为字符串。同样的,它也不是只读属性,所以我们也可以像hash属性一样为它赋值:

    const exampleUrl = new URL('http:// huozige.grapecity.com.cn:8080/功能演示');
    exampleUrl.host = 'es.grapecity.com.cn:80';
    console.log(exampleUrl);

    这样我们一样能够获得全新的URL。

    Hostname 属性

    使用hostname属性,可以从URL得到端口外的主机名:

    const exampleUrl = new URL('http:// huozige.grapecity.com.cn:8080/功能演示');
    console.log(exampleUrl.hostname)

    你同样也可以像修改其他属性一样修改hostname属性,例如:

    exampleUrl.hostname = ‘newExample.com’;

    Href 属性

    URL对象的href属性包含了传入URL对象的整个地址字符串,例如:

    const exampleUrl = new URL('https://www.grapecity.com.cn/developer/spreadjs#price');
    console.log(exampleUrl.href);

    打出来的就是我们传给URL构造函数的内容,和其他属性一样,href属性也不是只读的。

    Origin 属性

    区别于其他属性,Origin是一个只读属性,它将为你返回具有URL来源的Unicode序列化USVString。Origin的结构是由传入的URL类型决定的,对于http或https 的链接,得到的Origin将会为 协议(http/https)+ (://) + 域名 + (:端口),一般情况下,默认端口将会被忽略。对于BLOB 链接,Origin返回的则是BLOB:后面的部分。例如:

    const url1 = new URL("https://www.grapecity.com.cn/:443")
    const url2 = new URL("blob:https://www.grapecity.com.cn/:443")
    console.log(url1.origin);
    console.log(url2.origin)

    你将会得到

    https://www.grapecity.com.cn

    UserName & Password属性

    UserName和Password属性也是可写属性,它能提取域名前的用户名和密码部分的内容,例如:

    const url = new URL('https://username:password@www.grapecity.com.cn');
    console.log(url.username);
    console.log(url.password);
    url.username = “username1”;
    url.password = “password1”;
    console.log(url.username);
    console.log(url.password);

    Pathname属性

    这个属性是指获得传入url的第一个斜杠(/) 后面除参数外的部分,例如:

    const url = new URL ("https://www.grapecity.com.cn/developer/spreadjs#price")
    console.log(url.pathname);

    Port属性

    Port属性是指可以获得传入Url地址的端口值,这个属性也是可写的。

    const url = new URL('http://huozige.grapecity.com.cn:8080/功能演示');
    console.log(url.port);

    Protocol属性

    可以获得传入Url地址参数的协议名,一般是指类似http:,https:,ftp:,file:等这样的协议。

    const url = new URL('https://www.grapecity.com.cn/');
    console.log(url.protocol);

    Search属性

    可以获得传入Url地址参数?后的部分,但该属性只能获得整个查询字符串,如若需要了解各个参数的值,可以使用searchParams属性。

    const url = new URL('https://www.grapecity.com.cn:443?key1=value1&key2=value2');
    console.log(url.search);

    searchParams属性

    search属性只为我们获取了整个参数字符串,如果有把字符串解析为键值对,这时候searchParams属性就派上了用场,该属性将获得一个URLSearchParams对象,该对象具有列出查询字符串键值对列表的能力,例如,要获取参数列表,我们可以这样使用。

    const url = new URL(' https://www.grapecity.com.cn/?key1=value1&key2=value2'); 
    console.log(url.searchParams.get('key1')); 
    console.log(url.searchParams.get('key2'));

    从第一个console.log语句中获得value1,从第二个console.log语句中获得value2。URLSearchParams对象有一个get方法,通过键名获取给定查询字符串键的值。

    静态方法

    URL构造函数里有2个静态方法,它有createObjectURL()方法和revokeObjectURL()方法。

    URL.createObjectURL()静态方法会创建一个 DOMString,其中包含一个表示参数中给出的对象的URL。这个 URL 的生命周期和创建它的窗口中的 document 绑定。这个新的URL 对象表示指定的 File 对象或 Blob 对象。

    URL.revokeObjectURL()方法会释放一个通过URL.createObjectURL()创建的对象URL. 当你要已经用过了这个对象URL,然后要让浏览器知道这个URL已经不再需要指向对应的文件的时候,就需要调用这个方法。

    总结

    最后为大家带来一张表,希望能更好的帮助大家通览

     

    有了URL对象,操纵和从URL中提取部分不再是一件痛苦的事情,因为我们不必自己编写所有代码来完成这项工作。大多数浏览器的标准库中都内置了URL对象。现在我们可以将URL作为字符串传递给URL构造函数并创建URL的实例。然后,我们可以使用方便的值属性和方法来操作并获得我们想要的URL部分。

    最后,有什么问题,欢迎直接留言。

  • 相关阅读:
    Working with macro signatures
    Reset and Clear Recent Items and Frequent Places in Windows 10
    git分支演示
    The current .NET SDK does not support targeting .NET Core 2.1. Either target .NET Core 2.0 or lower, or use a version of the .NET SDK that supports .NET Core 2.1.
    Build website project by roslyn through devenv.com
    Configure environment variables for different tools in jenkins
    NUnit Console Command Line
    Code Coverage and Unit Test in SonarQube
    头脑王者 物理化学生物
    头脑王者 常识,饮食
  • 原文地址:https://www.cnblogs.com/powertoolsteam/p/urlobject.html
Copyright © 2011-2022 走看看