I do not have experience with regex, I found this in code and I am trying to understand it. This is regexp: (/[a-z\d]+=[a-z\d]+/gi);
And context in which is used is next:
const queryString = window.location.search;
let matches = queryString.match(/[a-z\d]+=[a-z\d]+/gi);
let count = matches ? matches.length : 0;
Also, I am interested is this possible to write in a different way, not to use regexp?
It's checking how many query strings are in the url.
/[a-z\d]+=[a-z\d]
says any letter or digit between an =
and another letter or digit should match.
The gi
part means it is global case insensitive.
g
= global, match all instances of the pattern in a string, not just onei
= case-insensitive (so, for example, /a/i will match the string "a" or "A".const urlQueryString = 'https://test.com/page?name=ferret&color=purple'
let matches = urlQueryString.match(/[a-z\d]+=[a-z\d]+/gi);
let count = matches ? matches.length : 0;
console.log(count) // --> 2 name=ferret color=purple
There is a tool available here allowing you to test the regex.
This code will count amount of query parameters present in string. However, you can use URLSearchParams
class for counting entries in query strings.
// URL: https://example.com/?query1=value&query2=value
const searchParams = new URLSearchParams(window.location.search);
// This row will map iterator into array
// [ ['query1', 'value'], ['query2', 'value'] ]
const entriesArray = [...searchParams.entries()];
// 2
console.log(entriesArray.length);