Table of Contents
1. 获取方式总结
2. 具体实现方法
2.1 正则匹配法
2.2 利用a标签
2.3 split分割法
2.4 URLSearchParams方法
Summary
Home Web Front-end JS Tutorial How to get URL parameters in JavaScript? Detailed explanation of 4 common methods

How to get URL parameters in JavaScript? Detailed explanation of 4 common methods

Mar 17, 2022 am 11:02 AM
javascript

如何利用原生JavaScript来获取URL链接参数?下面本篇文章给大家详细介绍4种常见的原生JS方法,希望对大家有所帮助!

How to get URL parameters in JavaScript? Detailed explanation of 4 common methods

作为一个前端开发,我们很多时候都需要对URL进行操作和处理,最常见的一种就是获取URL链接中携带的参数值了。使用框架开发的小伙伴可能会觉得这很简单,因为框架提供了很多方法让我们方便的获取URL链接携带的参数。但是有些时候我们不能依赖框架,需要我们使用原生JS去获取参数,这也是面试中经常遇到的一道题。今天我们就手撕代码,利用原生JS去获取URL链接参数值。

1. 获取方式总结

利用原生JS获取URL链接参数的方法也有好几种,今天我们依次来讲解常见的几种:

  • 通过正则匹配的方式

  • 利用a标签内置方法

  • 利用split方法分割法

  • 使用URLSearchParams方法

【相关推荐:javascript学习教程

2. 具体实现方法

2.1 正则匹配法

这是非常中规中举的一种方法,重点是要求我们要懂正则表达式。

代码如下:

<script>
  // 利用正则表达式
  let url = "http://www.baidu.com?name=elephant&age=25&sex=male&num=100"
  // // 返回参数对象
  function queryURLParams(url) {
    let pattern = /(\w+)=(\w+)/ig; //定义正则表达式
    let parames = {}; // 定义参数对象
    url.replace(pattern, ($, $1, $2) => {
      parames[$1] = $2;
    });
    return parames;
  }
  console.log(queryURLParams(url))
</script>
Copy after login

上段代码中重点是正则表达式的定义以及replace方法的使用,其中1、$2分别代表name=elephant、name、elephant,以此类推。replace结合正则更加详细的使用方法可以自行下去学习。

实现效果:

How to get URL parameters in JavaScript? Detailed explanation of 4 common methods

2.2 利用a标签

这种方法较少人使用,因为毕竟有点黑科技的意思在里面。它的原理主要就是利用了a标签得到一些内置属性,如href、hash、search等属性。

How to get URL parameters in JavaScript? Detailed explanation of 4 common methods

How to get URL parameters in JavaScript? Detailed explanation of 4 common methods

代码如下:

<script>
  let URL = "http://www.baidu.com?name=elephant&age=25&sex=male&num=100#smallpig"
  function queryURLParams(url) {
    // 1.创建a标签
    let link = document.createElement(&#39;a&#39;);
    link.href = url;
    let searchUrl = link.search.substr(1); // 获取问号后面字符串
    let hashUrl = link.hash.substr(1); // 获取#后面的值
    let obj = {}; // 声明参数对象
    // 2.向对象中进行存储
    hashUrl ? obj[&#39;HASH&#39;] = hashUrl : null; // #后面是否有值

    let list = searchUrl.split("&");
    for (let i = 0; i < list.length; i++) {
      let arr = list[i].split("=");
      obj[arr[0]] = arr[1];
    }
    return obj;
  }
  console.log(queryURLParams(URL))
</script>
Copy after login

上段代码中先创建了一个a标签,然后就可以根据a标签的属性分别得到url的各个部分了,这其实和Vue的路由跳转获取参数有点类似。

实现效果:

How to get URL parameters in JavaScript? Detailed explanation of 4 common methods

2.3 split分割法

该种方法利用了split可以以某个字符讲字符串分割为数组的特点,巧妙地将各个参数分割出来。

代码如下:

<script>
  let URL = "http://www.baidu.com?name=elephant&age=25&sex=male&num=100"
  function queryURLParams(URL) {
    // const url = location.search; // 项目中可直接通过search方法获取url中"?"符后的字串
    let url = URL.split("?")[1];
    let obj = {}; // 声明参数对象
    let arr = url.split("&"); // 以&符号分割为数组
    for (let i = 0; i < arr.length; i++) {
      let arrNew = arr[i].split("="); // 以"="分割为数组
      obj[arrNew[0]] = arrNew[1];
    }
    return obj;
  }
  console.log(queryURLParams(URL))
</script>
Copy after login

上传代码中如果在实际项目中,可以直接利用location.search获取“?”后面的字符串,这里为了方便演示,所以利用split分割了以下。

实现效果:

How to get URL parameters in JavaScript? Detailed explanation of 4 common methods

2.4 URLSearchParams方法

URLSearchParams方法能够让我们非常方便的获取URL参数,但是存在一定的兼容性问题,官网的解释如下:

URLSearchParams 接口定义了一些实用的方法来处理 URL 的查询字符串。

该接口提供了非常的的方法让我们来处理URL参数,这里我们只介绍如何获取URL参数值,更加详细的使用方法大家可以参考官网。

代码如下:

<script>
  let URL = "http://www.baidu.com?name=elephant&age=25&sex=male&num=100"
  function queryURLParams(URL) {
    let url = URL.split("?")[1];
    const urlSearchParams = new URLSearchParams(url);
    const params = Object.fromEntries(urlSearchParams.entries());
    return params
  }
  console.log(queryURLParams(URL))
</script>
Copy after login

这里我们基本上只用了两行主要代码就实现了参数的解析。需要注意的是urlSearchParams.entries()返回的是一个迭代协议iterator,所以我们需要利用Object.fromEntries()方法将把键值对列表转换为一个对象。

关于迭代协议,大家可以参考官网:

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Iteration_protocols

实现效果:

How to get URL parameters in JavaScript? Detailed explanation of 4 common methods

Compatibility:

How to get URL parameters in JavaScript? Detailed explanation of 4 common methods

You can see that our interface is not compatible with IE, the source of all evil.

Summary

Here are four methods to implement the parsing of URL link parameter values, among which the split method should be the most widely used. As a rising star, urlSearchParams is gradually recognized by everyone, and there are many ways to make it compatible with IE.

[Related video tutorial recommendations: web front-end]

The above is the detailed content of How to get URL parameters in JavaScript? Detailed explanation of 4 common methods. 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)

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.

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

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript and WebSocket: Building an efficient real-time image processing system JavaScript and WebSocket: Building an efficient real-time image processing system Dec 17, 2023 am 08:41 AM

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data

See all articles