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.
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
MethodThis 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
MethodAs 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
Methodhas
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
MethodgetAll
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.
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!