


How to get URL parameters in JavaScript? Detailed explanation of 4 common methods
如何利用原生JavaScript来获取URL链接参数?下面本篇文章给大家详细介绍4种常见的原生JS方法,希望对大家有所帮助!
作为一个前端开发,我们很多时候都需要对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>
上段代码中重点是正则表达式的定义以及replace方法的使用,其中1、$2分别代表name=elephant、name、elephant,以此类推。replace结合正则更加详细的使用方法可以自行下去学习。
实现效果:
2.2 利用a标签
这种方法较少人使用,因为毕竟有点黑科技的意思在里面。它的原理主要就是利用了a标签得到一些内置属性,如href、hash、search等属性。
代码如下:
<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('a'); link.href = url; let searchUrl = link.search.substr(1); // 获取问号后面字符串 let hashUrl = link.hash.substr(1); // 获取#后面的值 let obj = {}; // 声明参数对象 // 2.向对象中进行存储 hashUrl ? obj['HASH'] = 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>
上段代码中先创建了一个a标签,然后就可以根据a标签的属性分别得到url的各个部分了,这其实和Vue的路由跳转获取参数有点类似。
实现效果:
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>
上传代码中如果在实际项目中,可以直接利用location.search获取“?”后面的字符串,这里为了方便演示,所以利用split分割了以下。
实现效果:
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>
这里我们基本上只用了两行主要代码就实现了参数的解析。需要注意的是urlSearchParams.entries()返回的是一个迭代协议iterator,所以我们需要利用Object.fromEntries()方法将把键值对列表转换为一个对象。
关于迭代协议,大家可以参考官网:
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Iteration_protocols
实现效果:
Compatibility:
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!

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Dreamweaver Mac version
Visual web development tools

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function
