6

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
  • This is a duplicate question. Check this link stackoverflow.com/questions/901115/… Commented Dec 14, 2021 at 7: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 Commented Dec 14, 2021 at 7:42
  • You could just use window.location.origin if you need a base. Or get everything after the ? and pass it to URLSearchParams directly Commented Dec 14, 2021 at 7:47
  • @Reyno I think yours is the best proposal, feel free to post it as an answer and I'll approve it Commented Dec 14, 2021 at 8:14

4 Answers 4

8

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

Sign up to request clarification or add additional context in comments.

2 Comments

This does not work, if the url contains a "fragment" (#something at the end). For example http://www.example.com/abc?bar=baz#someSection
This doesn't work if the url contains multiple ?
2

Try this:

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

Comments

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

3 Comments

I think OP wanted to use builtin objects as much as possible, not reinvent the parsing mechanism. You're also only reinventing it partially, you're missing the decoding step for values.
@deceze Check my edited answer if it solves the problem.
Yeah, better. That's probably as good as it gets.
-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))

3 Comments

That would work if the search params was in my window.location, but I have the relative URL in a variable
@GabrielFurstenheim please see i have posted a updated function
Hi @Muhammad, parsing and decoding is hard and shouldn't be done with regexes. That's why I'm using built in functions

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.