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 Introduction to the method of parsing URLs in JavaScript (code example)

Introduction to the method of parsing URLs in JavaScript (code example)

Feb 25, 2019 am 10:22 AM
javascript url front end programmer

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

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:

Introduction to the method of parsing URLs in JavaScript (code example)

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:

Introduction to the method of parsing URLs in JavaScript (code example)

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 will 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

Introduction to the method of parsing URLs in JavaScript (code example)

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.

端口号是服务器上用于获取数据的特定“通道” - 因此,如果我拥有 example.com,我可以在多个不同的端口上发送不同的数据。 但通常域名默认为一个特定端口,因此不需要端口号。 来看看 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

The above is the detailed content of Introduction to the method of parsing URLs in JavaScript (code example). 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

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.

Which AI programmer is the best? Explore the potential of Devin, Tongyi Lingma and SWE-agent Which AI programmer is the best? Explore the potential of Devin, Tongyi Lingma and SWE-agent Apr 07, 2024 am 09:10 AM

On March 3, 2022, less than a month after the birth of the world's first AI programmer Devin, the NLP team of Princeton University developed an open source AI programmer SWE-agent. It leverages the GPT-4 model to automatically resolve issues in GitHub repositories. SWE-agent's performance on the SWE-bench test set is similar to Devin, taking an average of 93 seconds and solving 12.29% of the problems. By interacting with a dedicated terminal, SWE-agent can open and search file contents, use automatic syntax checking, edit specific lines, and write and execute tests. (Note: The above content is a slight adjustment of the original content, but the key information in the original text is retained and does not exceed the specified word limit.) SWE-A

PHP and Vue: a perfect pairing of front-end development tools PHP and Vue: a perfect pairing of front-end development tools Mar 16, 2024 pm 12:09 PM

PHP and Vue: a perfect pairing of front-end development tools. In today's era of rapid development of the Internet, front-end development has become increasingly important. As users have higher and higher requirements for the experience of websites and applications, front-end developers need to use more efficient and flexible tools to create responsive and interactive interfaces. As two important technologies in the field of front-end development, PHP and Vue.js can be regarded as perfect tools when paired together. This article will explore the combination of PHP and Vue, as well as detailed code examples to help readers better understand and apply these two

Revealing the appeal of C language: Uncovering the potential of programmers Revealing the appeal of C language: Uncovering the potential of programmers Feb 24, 2024 pm 11:21 PM

The Charm of Learning C Language: Unlocking the Potential of Programmers With the continuous development of technology, computer programming has become a field that has attracted much attention. Among many programming languages, C language has always been loved by programmers. Its simplicity, efficiency and wide application make learning C language the first step for many people to enter the field of programming. This article will discuss the charm of learning C language and how to unlock the potential of programmers by learning C language. First of all, the charm of learning C language lies in its simplicity. Compared with other programming languages, C language

Questions frequently asked by front-end interviewers Questions frequently asked by front-end interviewers Mar 19, 2024 pm 02:24 PM

In front-end development interviews, common questions cover a wide range of topics, including HTML/CSS basics, JavaScript basics, frameworks and libraries, project experience, algorithms and data structures, performance optimization, cross-domain requests, front-end engineering, design patterns, and new technologies and trends. . Interviewer questions are designed to assess the candidate's technical skills, project experience, and understanding of industry trends. Therefore, candidates should be fully prepared in these areas to demonstrate their abilities and expertise.

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

Is Django front-end or back-end? check it out! Is Django front-end or back-end? check it out! Jan 19, 2024 am 08:37 AM

Django is a web application framework written in Python that emphasizes rapid development and clean methods. Although Django is a web framework, to answer the question whether Django is a front-end or a back-end, you need to have a deep understanding of the concepts of front-end and back-end. The front end refers to the interface that users directly interact with, and the back end refers to server-side programs. They interact with data through the HTTP protocol. When the front-end and back-end are separated, the front-end and back-end programs can be developed independently to implement business logic and interactive effects respectively, and data exchange.

See all articles