DEV Community

WangLiwen
WangLiwen

Posted on

Use regular expressions to get url parameters in JS

In JavaScript, you can use regular expressions to extract URL parameters. Here's an example function that takes a URL string as input and returns an object containing all the parameters and their values:

function getURLParams(url) {  
  const searchParams = new URLSearchParams(url);  
  const params = {};  
  searchParams.forEach((value, key) => {  
    params[key] = value;  
  });  
  return params;  
}
Enter fullscreen mode Exit fullscreen mode

This function uses the URLSearchParams class to parse the query parameters in the URL and returns an object containing the parameter names and their corresponding values. If you prefer to use regular expressions to parse the URL parameters, you can use the following code:

function getURLParamsRegex(url) {  
  const regex = /[?&]([^=]+)=([^&]+)/g;  
  const params = {};  
  let match;  
  while ((match = regex.exec(url)) !== null) {  
    params[match[1]] = match[2];  
  }  
  return params;  
}
Enter fullscreen mode Exit fullscreen mode

This function uses the regular expression /?&=([^&]+)/g to match the URL parameters and stores each parameter name and value in an object. It then returns this object.

Top comments (0)