Home >Web Front-end >JS Tutorial >Introduction to URL-related content in JavaScript (with code)

Introduction to URL-related content in JavaScript (with code)

不言
不言forward
2019-03-29 09:31:112198browse

This article brings you an introduction to URLs in JavaScript (with code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Accompanied by the WeChat message prompt, Xiaosi sent a piece of code saying that he didn’t know why the page data could not be requested:

axios.get('users', {
    params: { ids: [1, 2, 3] }
})

Xiaoer saw that it was most likely caused by the array transfer method in query. , due to the backend implementation of parsing the array ids:[5, 6, 100], there may be the following methods:

bracket: ids[]=1&ids[]=2&ids[]=3
index: ids [0]=1&ids[1]=2&ids[3]=3
comma: ids=1,2,3
none: ids=1&ids=2&ids=3

After the four tests respectively The problem was solved, which also reminded Xiao Er that Brother Little Panda also encountered this problem when he was developing. After searching online, he found that others used the stringify direct code in the qs library and tried it without any errors. No matter how it works, What it is, it’s scary to think about it now.

Although we deal with URLs every day, not everyone understands them.

Not everyone will delve into why the code can run.

Return to original form

Use the URL() object to quickly return a url address to its original form:

Script

const url = new URL('http://www.pushme.top/users?sort_by=asc#page=userlist')
console.log(url)
Output
{
    hash: "#page=userlist"
    host: "www.pushme.top"
    hostname: "www.pushme.top"
    href: "http://www.pushme.top/users?sort_by=asc#page=userlist"
    origin: "http://www.pushme.top"
    password: ""
    pathname: "/users"
    port: ""
    protocol: "http:"
    search: "?sort_by=asc"
    searchParams: URLSearchParams {}
    username: ""
}

I didn’t expect that there are so many attributes in a small url address. Here we will mainly explain hash and search.

It is recommended to open the console and run the script, so that you don’t need to look up and down when reading.

host and hostname

Sharp-eyed students must have discovered that host and hostname are exactly the same. Why is this?

Recall localhost:8080 that we often see in development. The port number 8080 appears here, but when we usually visit some websites, we do not bring the port number. This is because the default port number of the url address is 80, so if you look carefully, you will find that the value of port above is empty.

The difference between host and hostname is that when there is a port, host will include the port number, but hostname will not.

protocol and origin

protocol refers to the protocol. The most common ones are http and https. Of course, now the browser will automatically add it for you when you do not enter the protocol, but in URL() it is not If you bring the agreement, you will get an error. Origin is composed of protocol and host.

search and searchParams

Basics

?search=a The query starts with the first ? and ends with the end of the line or #. Used to pass some data to the backend. The data is separated by & and the value is separated by =. Let’s understand it through a piece of code:

const query = 'id=1&sort=asc&hello=world';
// 对 & 分割取得数据对
const data = query.split('&').reduce((data,keyValue) => {
    const [ key, value ] = keyValue.split('=');
    return (data[key] = value, data);
}, {});

// 输出 {id: "1", sort: "asc", hello: "world"}
console.log(data);

This is the most basic combination of data pairs in query. Of course, the first four array expressions require additional processing, which is nothing more than the collection and collection of keys. value judgment. However, this part is basically handled by the back-end framework for us. The front-end can also be completed using libraries such as qs, query-string, and qss.

Digression: These libraries have very little code, so it’s worth reading and you may gain something new.

Plus sign and space

I don’t know if you have paid attention to these details in Baidu and Google that you use every day:

Enter https://www.baidu. com/s?wd=Xiaoer pushmetop What appears in the search box is Xiaoer pushmetop, and the URL address in the address bar magically turns into a space.
Enter https://www.baidu.com/s?wd=小二 pushmetop. What appears in the search box is Xiaoer pushmetop, and the space in the URL address in the address bar changes to .
Enter https://www.baidu.com/s?wd=小二+pushmetop. What appears in the search box is Xiaoer pushmetop, and the + in the URL address in the address bar becomes .

For specific reasons, you can check Wikipedia about percent encoding of reserved characters.

URL encoding

Clicking on links on websites such as Nuggets will quickly flash a URL address similar to http://www.pushmetop.com?redirect=xxxxx, and you will find the redirect corresponding to redirect The address will be a bunch of garbled % characters. Why is this?

Let us assume that the link that needs to be jumped is www.test.com?hello=world&id=1. Splicing the entire link together is:

http://www.pushmetop.com?redirect=www.test.com?hello=world&id=1

According to the initial definition The parsed value and expected value are completely different:

parsed value
{
    "redirect": "www.test.com?hello=world",
    "id": "1"
}
expected value
{
    "redirect": "www.test.com?hello=world&id=1"
}

In order to solve this problem, URL was born Encoding to solve the problem:

encodeURIComponent() and decodeURIComponent() are recommended.

Comparing encodeURI() and decodeURI(), the former will not encode the characters "; / ? : @ & = $ , #".

escape() and unescape() are not recommended.

example

let redirect = 'www.test.com?hello=world&id=1';
redirect = encodeURIComponent(redirect);

let url = `http://www.pushmetop.com?redirect=${redirect}`;
url = new URL(url)

// 输出: www.test.com?hello=world&id=1
console.log(url.searchParams.get('redirect'))

hash

#hash 中 fragment 以 # 为开始 行尾 为结束。在 回到顶部 中有提到过利用hash锚点来进行跳转,如果大家注意观察的话会发现 hash 的改变不会引起页面的刷新。

在 Angular.js、Vue Router 等库中,会利用在 html5 中提供了 history 的一系列操作,来帮助我们不刷新页面管理  url。但是在一些旧的浏览器上并不兼容时,会利用 hash 不会主动触发浏览器 reload 的特性来修改 location.hash 来管理路由。 当然 hash 的另外一个特点是可以被保存为书签,也是一大优点。

hash 的小妙用也可以像 query 那样利用 & 和 = 来存取数据,当然你也可以定制属于你的规则。

href 和 pathname

href 为整个 url地址。而 pathname 属性包含 URL 的整个路径部分。它跟在 host (包括 port)后面,排在 query 或 hash 组成部分的前面且被 ASCII 问号(?)或哈希字符(#)分隔。

username 和 password

username 和 password 在日常使用中很少用,它们可以合称为 auth。该字符串跟在 protocol 和双斜杠(如果有)的后面,排在 host 部分的前面且被一个 ASCII 的 at 符号(@)分隔:

http://username:password@www.pushme.top/test/blah?something=123

结尾

本来只是想讨论 hash 和 search ,结果全都过一遍,今天就辛苦大家了。

本篇文章到这里就已经全部结束了,更多其他精彩内容可以关注PHP中文网的的JavaScript教程视频栏目!

The above is the detailed content of Introduction to URL-related content in JavaScript (with code). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete