4

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?

Gabriel Furstenheim
  • 2,969
  • 30
  • 27
  • This is a duplicate question. Check this link https://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript – VeteranSlayer Dec 14 '21 at 07:37
  • 4
    @VeteranSlayer how is that a duplicate? In that question they have an URL, not an URI. My problem is that the only way that I know is to first create an URL and then use that question. But creating the url seems to require a random base – Gabriel Furstenheim Dec 14 '21 at 07:42
  • You could just use `window.location.origin` if you need a base. Or get everything after the `?` and pass it to [URLSearchParams](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams/URLSearchParams) directly – Reyno Dec 14 '21 at 07:47
  • @Reyno I think yours is the best proposal, feel free to post it as an answer and I'll approve it – Gabriel Furstenheim Dec 14 '21 at 08:14

4 Answers4

4

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' ) );
Reyno
  • 6,119
  • 18
  • 27
1

Try this:

const paramString = "/a/b?someParam=cccc".split("?")[1];
const params = new URLSearchParams(paramString);
const result = Object.fromEntries(params.entries());
console.log(result);
deceze
  • 510,633
  • 85
  • 743
  • 889
peaxkl
  • 71
  • 4
-1

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"));
VeteranSlayer
  • 294
  • 2
  • 7
-2

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))