I have below logic to retrieve query PARAM form the application url. But this logic is not working when there is a url as a query param which has its own query parameters. Example below
Ex: https://test.domain.com?param1=a&ru=**https://url2.domain.com/?url2paramA=A&url2paramB=B**
In this example url2param2 is part of ru(redirect URL). when I try to retrieve ru parameter, its only giving the url part with first parameter in it. Second query parameter its considered as part of main URL.
Current Logic
const getParameterByName = (name, search) => {
const match = RegExp('[?&]' + name + '=([^&]*)').exec(search);
try {
return match && decodeURIComponent(match[1].replace(/+/g, ' '));
} catch {
return match && match[1];
}
};
var result = getParameterByName('ru', 'https://test.domain.com?param1=a&ru=https://url2.domain.com/?url2paramA=A&url2paramB=B');
console.log(result)
3
Answers
As mentioned in the comments, you may use the
URL
andURLSearchParams
APIs:EDIT:
If you want to consider
paramB
as part of theru
, you would have toencodeURIComponent
the second URL:This is because your redirect url is not encoded
Your code works perfectly, but in this code you extract the url between
&
using regex that’s why you didn’t get theurl2paramB=B
after&
, but you need to pass the redirect URL between any special characters like your given URL.https://test.domain.com?param1=a&ru=**https://url2.domain.com/?url2paramA=A&url2paramB=B**
This URL contains a special character (two asterisks(
**
)) so you can extract the redirect URL between these asterisks(*
).Try this code: