Parse search params in relative URL in Javascript

Viewed 1139

I have a relative URL, something like /a/b?someParam=cccc

I want to extract the value of the parameter. One alternative is to do (new URL(myUri, 'http://example.com')).searchParams.get('someParam'). It is nice because it uses the built-in functions from the browser and it is going to be safe in cases when the parameter of the url is encoded.

However, it depends on a random base of the url http://example.com. Is there a way to parse a URL without a base? Or to extract the search params?

4 Answers

You could take everything after the ? and pass it directly to URLSearchParams.

const getParamsFromURI = ( uri ) => {
  // Get everything after the `?`
  const [ , paramString ] = uri.split( '?' );

  // Return parameters
  return new URLSearchParams( paramString );
};

const params = getParamsFromURI( '/a/b?someParam=cccc' );
console.log( params.get( 'someParam' ) );

Or if you want to use the URL constructor you can get a base from window.location.origin

const getParamsFromURI = ( uri ) => {
  // Create url with base
  const base = window.location.origin; // Could also be a fixed value e.g. http://example.com
  const url = new URL( uri, base );
  
  // Return parameters
  return url.searchParams;
};

const params = getParamsFromURI( '/a/b?someParam=cccc' );
console.log( params.get( 'someParam' ) );

Try this:

const paramString = "/a/b?someParam=cccc".split("?")[1];
const params = new URLSearchParams(paramString);
const result = Object.fromEntries(params.entries());
console.log(result);

You could manipulate the string like this

var test = "/a/b?someParam=cccc&someotherparam=bbb";
var params = test.split('?')[1].split('&').map( (e) => {
    let temp = e.split('=');
    let rObj = {};
   rObj[temp[0]] = temp[1];
   return rObj;
} );

console.log(params);

At first you split the string to two segments (before and after "?"). Then you split again the second part by the "&" symbol to generate an array of strings. In the end you map the array to generate an object with keys and values.

I hope the helps.

EDIT

If you want to use the method URLSearchParams you could do it like this

var test = "/a/b?someParam=cccc&someotherparam=bbb";

var params = new URLSearchParams(test.split('?')[1]);

console.log(params.get("someParam"));

var url_string = "/a/b?someParam=cccc";

function getParam( name, url ) {

if (!url) url = location.href;
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( url );
return results == null ? null : results[1];

}

console.log(getParam('someParam', url_string))

Related