Method 1: Modern browsers support URL and URLSearchParams objects, which can easily extract parameters from URLs.
// Assume that the current URL is "/?name=John&age=30"const url = new URL(); // Or you can directly pass a URL stringconst name = ('name'); // "John" const age = ('age'); // "30" (name, age);
Method 2: Use regular expressions
You can use regular expressions to match URL parameters, which is relatively inefficient and complex, but can also be done.
function getQueryParam(name) { const regex = new RegExp('[?&]' + name + '=([^&#]*)', 'i') const results = () return results ? decodeURIComponent(results[1]) : null } // Assume that the current URL is "/?name=John&age=30"const name = getQueryParam('name'); // "John" const age = getQueryParam('age'); // "30" (name, age)
Method 3: Use split and reduce
You can manually split the query parameters through the split method and convert them into objects with reduce.
function getQueryParams() { return .substring(1) // Remove? .split('&') // Press & split .reduce((params, param) => { const [key, value] = ('='); params[decodeURIComponent(key)] = decodeURIComponent(value || ''); return params; }, {}); } // Assume that the current URL is "/?name=John&age=30"const params = getQueryParams(); const name = params['name'];// "John" const age = params['age']; // "30" (name, age);
Method 4: Use and custom functions
existConstruct your own parsing function on it, this method is relatively simple.
function getQueryParameter(name) { const params = new URLSearchParams() return (name) } // Assume that the current URL is "/?name=John&age=30"const name = getQueryParameter('name'); // "John" const age = getQueryParameter('age'); // "30" (name, age)
Summarize
This is the end of this article about four methods of obtaining parameter values in a URL in JavaScript. For more related content on obtaining URL parameter values in JS, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!