search
HomeWeb Front-endJS TutorialHow to get query string in JavaScript

How to get query string in JavaScript

In this short article, we will discuss a few different ways to get a query string in JavaScript.

When you use JavaScript, sometimes you need to access query string parameters in your script. There is no direct way to achieve this, as there are no built-in JavaScript functions or methods that allow you to achieve it. Of course, you can find a lot of third-party utility scripts that suit your requirements, but it's better to do it using plain JavaScript.

In this article, we will discuss how to build a custom function to get query string parameters in plain JavaScript. Later, we'll also explore the URLSearchParams interface to understand how it works and how it helps with handling query string parameters.

How to get query string in Vanilla JavaScript

In this section, we will see how to get the query string value using plain JavaScript.

Let’s take a look at the following JavaScript example.

function getQueryStringValues(key) {
    var arrParamValues = [];
    var url = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');

    for (var i = 0; i < url.length; i++) {
        var arrParamInfo = url[i].split('=');

        if (arrParamInfo[0] == key || arrParamInfo[0] == key+'[]') {
            arrParamValues.push(decodeURIComponent(urlparam[1]));
        }
    }

    return (arrParamValues.length > 0 ? (arrParamValues.length == 1 ? arrParamValues[0] : arrParamValues) : null);
}

// index.php?keyword=FooBar&hobbies[]=sports&hobbies[]=Reading
console.log(getQueryStringValues('keyword')); // "FooBar"
console.log(getQueryStringValues('hobbies')); // Array [ "sports", "Reading" ]
console.log(getQueryStringValues('keyNotExits')); // null

We created the getQueryStringValues function that you can use to get the values ​​of the query string parameters available in a URL.

Let's take a look at the function and see how it works.

The following code snippet is one of the most important code snippets in this function.

var url = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');

First, we use the indexOf method to find the position of the ? characters in the URL. Next, we extract the query string portion of the URL using the slice method. Finally, we use the split method to split the query string by & characters. Therefore, the url variable is initialized using the query string parameter array.

Next, we loop through all elements of the url array. In the loop, we use the split method to split the array values ​​by = characters. In this way, the arrParamInfo variable is initialized with an array, where the array key is the parameter name and the array value is the parameter value. You can see this in the code snippet below.

var arrParamInfo = url[i].split('=');

Next, we compare it with the parameters passed in the function. If it matches the parameter passed in, we push the parameter value into the arrParamValues array. As you can see, we also introduced single parameters and array parameters.

if (arrParamInfo[0] == key || arrParamInfo[0] == key+'[]') {
    arrParamValues.push(decodeURIComponent(urlparam[1]));
}

Finally, if the arrParamValues variable contains a value, we will return it, otherwise null will be returned.

return (arrParamValues.length > 0 ? (arrParamValues.length == 1 ? arrParamValues[0] : arrParamValues) : null);

You can continue to test the getQueryStringValues function with different values.

As shown in the example above, we call it with different values ​​and log the output using the console.log function. Something to note is that if the parameter you pass in the getQueryStringValues function is present in the query string as an array, you will get an array in response and it will return all the values ​​of that parameter.

URLSearchParams Method

This is one of the easiest ways to get a query string value in JavaScript. URLSearchParams The interface provides utility methods to handle query strings for URLs. You can check browser support via "Can I use it?"

Let's take a quick look at how it works.

// index.php?keyword=Search Text&click=Submit
var urlParams = new URLSearchParams(window.location.search);

After initializing the URLSearchParams object with a query string, you can use the utility methods provided by the URLSearchParams object.

Let us introduce some useful methods in this article.

get Method

As the name suggests, the get method is used to obtain the value of the query string parameter.

Let us try to understand it with the following example.

// index.php?keyword=Search Text&click=Submit
var objUrlParams = new URLSearchParams(window.location.search);
console.log(objUrlParams.get('keyword')); // “Search Text”

In the above example, we get the value of the keyword query string parameter, which will output the search text.

This way you can use the get method to get the value of any query string parameter.

has Method

has method is used to check whether parameters exist in the query string.

// index.php?keyword=Search Text&click=Submit
var objUrlParams = new URLSearchParams(window.location.search);
console.log(objUrlParams.has('order')); // “false”
console.log(objUrlParams.has('click')); // “true”

In the above example, we used the has method to check whether different parameters exist.

getAll Method

getAll method is used to get all values ​​of a parameter when it exists multiple times.

Let's check it out with the following example.

// index.php?keyword=Search Text&click=Submit&filter=value1&filter=value2
var objUrlParams = new URLSearchParams(window.location.search);
console.log(objUrlParams.getAll('filter')); // [“value1”,”valu2”]

As you can see, when we use the getAll method, it returns all the values ​​associated with that parameter.

in conclusion

Today, we discussed the different methods you can use to get query strings in JavaScript. In addition to plain JavaScript, we also discussed how to obtain query string variables using the URLSearchParams interface.

The above is the detailed content of How to get query string in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
演示win7调整屏幕亮度的方法演示win7调整屏幕亮度的方法Jul 08, 2023 pm 07:49 PM

不同的电脑系统在调整屏幕亮度的操作方法上会有些不同,最近就有使用win7系统的网友不知道win7怎么调整屏幕亮度,看久了电脑眼睛比较酸痛。下面小编就教下大家win7调整屏幕亮度的方法。具体的操作步骤如下:1、点击win7电脑左下角的“开始”,在弹出的开始菜单中选择“控制面板”打开。2、在打开的控制面板中找到“电源选项”打开。3、也可以用鼠标右键电脑右下角的电源图标,在弹出的菜单中,点击“调整屏幕亮度”,如下图所示。两种方法都可以用。4、在打开的电源选项窗口的最下面可以看到屏幕亮度调整的滚动条,直

win10监控摄像头打开照片的方法win10监控摄像头打开照片的方法Jul 10, 2023 pm 09:41 PM

如果我们手头没有手机,只有电脑,但我们必须拍照,我们可以使用电脑内置的监控摄像头拍照,那么如何打开win10监控摄像头,事实上,我们只需要下载一个相机应用程序。打开win10监控摄像头的具体方法。win10监控摄像头打开照片的方法:1.首先,盘快捷键Win+i打开设置。2.打开后,进入个人隐私设置。3.然后在相机手机权限下打开访问限制。4.打开后,您只需打开相机应用软件。(如果没有,可以去微软店下载一个)5.打开后,如果计算机内置监控摄像头或组装了外部监控摄像头,则可以拍照。(因为人们没有安装摄

基于Java的机器视觉实践和方法介绍基于Java的机器视觉实践和方法介绍Jun 18, 2023 am 11:21 AM

随着科技的不断发展,机器视觉技术在各个领域得到了广泛应用,如工业自动化、医疗诊断、安防监控等。Java作为一种流行的编程语言,其在机器视觉领域也有着重要的应用。本文将介绍基于Java的机器视觉实践和相关方法。一、Java在机器视觉中的应用Java作为一种跨平台的编程语言,具有跨操作系统、易于维护、高度可扩展等优点,对于机器视觉的应用具有一定的优越性。Java

win7怎么调屏幕亮度的两种简单方法win7怎么调屏幕亮度的两种简单方法Jul 08, 2023 pm 06:33 PM

目前有很多屏幕亮度调整软件,我们可以通过使用软件进行快速调整或者通过显示器上自带的亮度功能进行调整。以下是详细的Win7屏幕亮度调整方式,您可以通过教程中的方法进行快速调整即可。Win7系统电脑怎么调节屏幕亮度教程:1、依次点击“计算机—右键—控制面板”,如果没有也可以在搜索框中进行搜索。2、点击控制面板下的“硬件和声音”,或者点击“外观和个性化”都可以。3、点击“NVIDIA控制面板”,有些显卡可能是AMD或者Intel的,请根据实际情况选择。4、调节图示中亮度滑块即可。5、还有一种方法,就是

PHP文件下载方法及常见问题解答PHP文件下载方法及常见问题解答Jun 09, 2023 pm 12:37 PM

PHP是一个广泛使用的服务器端编程语言,它的许多功能和特性可以将其用于各种任务,包括文件下载。在本文中,我们将了解如何使用PHP创建文件下载脚本,并解决文件下载过程中可能出现的常见问题。一、文件下载方法要在PHP中下载文件,我们需要创建一个PHP脚本。让我们看一下如何实现这一点。创建下载文件的链接通过HTML或PHP在页面上创建一个链接,让用户能够下载文件。

Go 语言中的方法是怎样定义和使用的?Go 语言中的方法是怎样定义和使用的?Jun 10, 2023 am 08:16 AM

Go语言是近年来备受青睐的编程语言,因其简洁、高效、并发等特点而备受开发者喜爱。其中,方法(Method)也是Go语言中非常重要的概念。接下来,本文就将详细介绍Go语言中方法的定义和使用。一、方法的定义Go语言中的方法是带有接收器(Receiver)的函数,它是一个与某个类型绑定的函数。接收器可以是值类型或者指针类型。用于接收者的参数可以在方法名

Vue 中的 createApp 方法是什么?Vue 中的 createApp 方法是什么?Jun 11, 2023 am 11:25 AM

随着前端开发的快速发展,越来越多的框架被用来构建复杂的Web应用程序。Vue.js是流行的前端框架之一,它提供了许多功能和工具来简化开发人员构建高质量的Web应用程序。createApp()方法是Vue.js中的一个核心方法之一,它提供了一种简单的方式来创建Vue实例和应用程序。本文将深入探讨Vue中createApp方法的作用,其如何使用以及使用时需要了解

使用PHP数组实现数据缓存和存储的方法和技巧使用PHP数组实现数据缓存和存储的方法和技巧Jul 16, 2023 pm 02:33 PM

使用PHP数组实现数据缓存和存储的方法和技巧随着互联网的发展和数据量的急剧增长,数据缓存和存储成为了我们在开发过程中必须要考虑的问题之一。PHP作为一门广泛应用的编程语言,也提供了丰富的方法和技巧来实现数据缓存和存储。其中,使用PHP数组进行数据缓存和存储是一种简单而高效的方法。一、数据缓存数据缓存的目的是为了减少对数据库或其他外部数据源的访问次数,从而提高

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

mPDF

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

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools