search
HomeWeb Front-endJS TutorialIntroduction to URL-related content in JavaScript (with code)

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. If there is any infringement, please contact admin@php.cn delete
Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment