search
HomeWeb Front-endJS TutorialDetailed explanation of how to use JavaScript to parse URLs

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>
    

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);

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');

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

console.log(myURL);

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

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:"

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"

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"

主机(host)

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

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

来源(origin)

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

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

pathname(文件名)

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

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

锚点(hash)

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

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

查询参数 (search)

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

?key1=value1&key2=value2&key3=value3

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

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

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

使用 URLSearchParams 解析查询参数

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

var searchParams = new URLSearchParams(myURL.search);

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

?x=y&a=b

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

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

扩展

获取 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"));

方法二: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
}

原文地址: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
This article is reproduced at:segmentfault. If there is any infringement, please contact admin@php.cn delete
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.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

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

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)