Table of Contents
Start
What is a URL
Get the current URL
Creating URL Objects
Structure of the URL object
href
Protocol
Hostname
Port
主机(host)
来源(origin)
pathname(文件名)
锚点(hash)
查询参数 (search)
使用 URLSearchParams 解析查询参数
扩展
获取 URL 的中参数
修改 URL 的中某个参数值
Home Web Front-end JS Tutorial Detailed explanation of how to use JavaScript to parse URLs

Detailed explanation of how to use JavaScript to parse URLs

Nov 26, 2020 pm 06:02 PM
javascript url

Detailed explanation of how to use JavaScript to parse URLs

In web development, there are many situations where URL needs to be parsed. This article mainly learns how to use the URL object to achieve this.

Start

Create an HTML file with the following content and open it in the browser.

    
        <title>JavaScript URL parsing</title>
    
    
        <script>
            // 激动人心的代码即将写在这里
        </script>
    
Copy after login

If you want to try anything in this article, put it in a <script> tag, save, reload the page, and see what happens! In this tutorial, console.log will be used to print the required content. You can open the development tools to view the content. </script>

What is a URL

This should be fairly simple, but let’s be clear. URL is the address of a web page that can be entered into a browser to obtain the unique content of that web page. You can see it in the address bar:

Detailed explanation of how to use JavaScript to parse URLs

A URL is a Uniform Resource Locator, a concise representation of the location and access method of a resource available from the Internet , is the address of a standard resource on the Internet. Every file on the Internet has a unique URL, which contains information indicating where the file is located and what the browser should do with it.

Also, if you are not familiar with how basic URL paths work, you can check out this article to learn.

URLs don’t all look the same

Here’s a quick reminder - sometimes URLs can be really weird, like this:

https://example.com: 1234/page/?a=b

http://localhost/page.html

https://154.23.54.156/page?x=...

file :///Users/username/folder/file.png

Get the current URL

Getting the URL of the current page is very simple - we can use window.location.

Try adding this to the script we wrote:

console.log(window.location);
Copy after login

Check the browser console:

Detailed explanation of how to use JavaScript to parse URLs

Not what you want? That's because it doesn't return the actual URL address you see in the browser - it returns a URL object. Using this URL object, we can parse different parts of the URL, which we will cover next.

Creating URL Objects

As you'll soon see, you can use URL objects to understand the different parts of a URL. What if you want to do this for any URL, not just the URL of the current page? We can do this by creating a new URL object. Here's how to create one:

var myURL = new URL('https://example.com');
Copy after login

It's that easy! You can print myURL to view the contents of myURL:

console.log(myURL);
Copy after login

Detailed explanation of how to use JavaScript to parse URLs

For the purposes of this article, set myURL to this value:

var myURL = new URL('https://example.com:4000/folder/page.html?x=y&a=b#section-2')
Copy after login

Copy and paste it into the <script></script> element so you can proceed! Some parts of this URL may be unfamiliar as they aren't always used - but you'll learn about them below, so don't worry!

Structure of the URL object

Using the URL object, you can get the different parts of the URL very easily. Here's everything you can get from the URL object. For these examples we will use myURL set above.

href

The href of a URL is basically the entire URL as a string (text). If you want the URL of the page as a string instead of a URL object, you can write window.location.href.

console.log(myURL.href);
// Output: "https://example.com:4000/folder/page.html?x=y&a=b#section-2"
Copy after login

Protocol

The protocol of the URL is the first part. This tells the browser how to access the page, such as via HTTP or HTTPS. But there are many other protocols, such as ftp (File Transfer Protocol) and ws (WebSocket). Typically, websites will use HTTP or HTTPS.

Although if you have a file open on your computer, you're probably using the file protocol! The protocol part of the URL object includes :, but does not include //. Let's take a look at myURL!

console.log(myURL.protocol);
// Output: "https:"
Copy after login

Hostname

The hostname is the domain name of the site. If you're not familiar with a domain name, it's the main part of the URL you see in your browser - such as google.com or codetheweb.blog.

console.log(myURL.hostname);
// Output: "example.com"
Copy after login

Port

The port number of the URL is located after the domain name and separated by a colon (for example, example.com:1234). Most URLs don't have a port number, which is very rare. The

port number is the specific "channel" on the server used to get the data - so if I have example.com, I can send different data on multiple different ports. But usually the domain name defaults to a specific port, so a port number is not required. Let’s take a look at the port number of myURL:

console.log(myURL.port);
// Output: "4000"
Copy after login

主机(host)

主机只是主机名端口放在一起,尝试获取 myURL 的主机:

console.log(myURL.host);
// Output: "example.com:4000"
Copy after login

来源(origin)

origin 由 URL 的协议,主机名和端口组成。 它基本上是整个 URL,直到端口号结束,如果没有端口号,到主机名结束。

console.log(myURL.origin);
// Output: "https://example.com:4000"
Copy after login

pathname(文件名)

pathname 从域名的最后一个 “/” 开始到 “?” 为止,是文件名部分,如果没有 “?” ,则是从域名最后的一个 “/” 开始到 “#” 为止 , 是文件部分, 如果没有 “?” 和 “#” , 那么从域名后的最后一个 “/” 开始到结束 , 都是文件名部分。

console.log(myURL.pathname);
// Output: "/folder/page.html"
Copy after login

锚点(hash)

“#” 开始到最后,都是锚部分。可以将哈希值添加到 URL 以直接滚动到具有 ID 为该值的哈希值 的元素。 例如,如果你有一个 idhello 的元素,则可以在 URL 中添加 #hello 就可以直接滚动到这个元素的位置上。通过以下方式可以在 URL 获取 “#” 后面的值:

console.log(myURL.hash);
// Output: "#section-2"
Copy after login

查询参数 (search)

你还可以向 URL 添加查询参数。它们是键值对,意味着将特定的“变量”设置为特定值。 查询参数的形式为 key=value。 以下是一些 URL 查询参数的示例:

?key1=value1&key2=value2&key3=value3
Copy after login

请注意,如果 URL 也有 锚点(hash),则查询参数位于 锚点(hash)(也就是 ‘#’)之前,如我们的示例 URL 中所示:

console.log(myURL.search);
// Output: "?x=y&a=b"
Copy after login

但是,如果我们想要拆分它们并获取它们的值,那就有点复杂了。

使用 URLSearchParams 解析查询参数

要解析查询参数,我们需要创建一个 URLSearchParams 对象,如下所示:

var searchParams = new URLSearchParams(myURL.search);
Copy after login

然后可以通过调用 searchParams.get('key')来获取特定键的值。 使用我们的示例网址 - 这是原始搜索参数:

?x=y&a=b
Copy after login

因此,如果我们调用 searchParams.get('x'),那么它应该返回 y,而 searchParams.get('a')应该返回 b,我们来试试吧!

console.log(searchParams.get('x'));
// Output: "y"
console.log(searchParams.get('a'));
// Output: "b"
Copy after login

扩展

获取 URL 的中参数

方法一:正则法

function getQueryString(name) {
    var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
    var r = window.location.search.substr(1).match(reg);
    if (r != null) {
        return unescape(r[2]);
    }
    return null;
}
// 这样调用:
alert(GetQueryString("参数名1"));
alert(GetQueryString("参数名2"));

alert(GetQueryString("参数名3"));
Copy after login

方法二:split拆分法

function GetRequest() {
    var url = location.search; //获取url中"?"符后的字串
    var theRequest = new Object();
    if (url.indexOf("?") != -1) {
        var str = url.substr(1);
        strs = str.split("&");
        for(var i = 0; i <h4 id="修改-URL-的中某个参数值">修改 URL 的中某个参数值</h4><pre class="brush:php;toolbar:false">//替换指定传入参数的值,paramName为参数,replaceWith为新值
function replaceParamVal(paramName,replaceWith) {
    var oUrl = this.location.href.toString();
    var re=eval('/('+ paramName+'=)([^&]*)/gi');
    var nUrl = oUrl.replace(re,paramName+'='+replaceWith);
    this.location = nUrl;
  window.location.href=nUrl
}
Copy after login

原文地址:https://codetheweb.blog/2019/01/21/javascript-url-parsing/

为了保证的可读性,本文采用意译而非直译。

更多编程相关知识,请访问:编程学习网站!!

The above is the detailed content of Detailed explanation of how to use JavaScript to parse URLs. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Why NameResolutionError(self.host, self, e) from e and how to solve it Why NameResolutionError(self.host, self, e) from e and how to solve it Mar 01, 2024 pm 01:20 PM

The reason for the error is NameResolutionError(self.host,self,e)frome, which is an exception type in the urllib3 library. The reason for this error is that DNS resolution failed, that is, the host name or IP address attempted to be resolved cannot be found. This may be caused by the entered URL address being incorrect or the DNS server being temporarily unavailable. How to solve this error There may be several ways to solve this error: Check whether the entered URL address is correct and make sure it is accessible Make sure the DNS server is available, you can try using the "ping" command on the command line to test whether the DNS server is available Try accessing the website using the IP address instead of the hostname if behind a proxy

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

What is the difference between html and url What is the difference between html and url Mar 06, 2024 pm 03:06 PM

Differences: 1. Different definitions, url is a uniform resource locator, and html is a hypertext markup language; 2. There can be many urls in an html, but only one html page can exist in a url; 3. html refers to is a web page, and url refers to the website address.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

See all articles