Home > Article > Web Front-end > Introduction to the method of parsing URLs in JavaScript (code example)
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.
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>
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:
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 sameHere’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
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:
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.
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');
It's that easy! You can print myURL
to view the contents of myURL
:
console.log(myURL);
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!
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.
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"
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:"
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"
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"
主机只是主机名
和端口
放在一起,尝试获取 myURL
的主机:
console.log(myURL.host); // Output: "example.com:4000"
origin 由 URL 的协议,主机名和端口组成。 它基本上是整个 URL,直到端口号结束,如果没有端口号,到主机名结束。
console.log(myURL.origin); // Output: "https://example.com:4000"
pathname
从域名的最后一个 “/” 开始到 “?” 为止,是文件名部分,如果没有 “?” ,则是从域名最后的一个 “/” 开始到 “#” 为止 , 是文件部分, 如果没有 “?” 和 “#” , 那么从域名后的最后一个 “/” 开始到结束 , 都是文件名部分。
console.log(myURL.pathname); // Output: "/folder/page.html"
从 “#” 开始到最后,都是锚部分。可以将哈希值添加到 URL 以直接滚动到具有 ID 为该值的哈希值 的元素。 例如,如果你有一个 id
为 hello
的元素,则可以在 URL 中添加 #hello
就可以直接滚动到这个元素的位置上。通过以下方式可以在 URL 获取 “#” 后面的值:
console.log(myURL.hash); // Output: "#section-2"
你还可以向 URL 添加查询参数。它们是键值对,意味着将特定的“变量”设置为特定值。 查询参数的形式为 key=value
。 以下是一些 URL 查询参数的示例:
?key1=value1&key2=value2&key3=value3
请注意,如果 URL 也有 锚点(hash),则查询参数位于 锚点(hash)(也就是 ‘#’)之前,如我们的示例 URL 中所示:
console.log(myURL.search); // Output: "?x=y&a=b"
但是,如果我们想要拆分它们并获取它们的值,那就有点复杂了。
要解析查询参数,我们需要创建一个 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"
方法一:正则法
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>修改 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 }
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!