React Native - Parse URL to get Query Variable
Asked Answered
I

8

29

Looking for a way to parse a URL to get a query variable in React Native received from Linking.

I'm receiving the URL as something like:

url-app-scheme://somePage?someVar=someVal

I'd like to get the someVar value from the URL.

Any thoughts?

Icecold answered 18/5, 2017 at 3:38 Comment(0)
D
29

This should do the trick

var url = "http://example.com?myVar=test&otherVariable=someData&number=123"

var regex = /[?&]([^=#]+)=([^&#]*)/g,
  params = {},
  match;
while (match = regex.exec(url)) {
  params[match[1]] = match[2];
}
console.log(params)
Dim answered 18/5, 2017 at 22:2 Comment(4)
If someone wants explanation then please see this reference, also thanks @Ray, ref=https://www.jskap.com/blog/React-Native-parse-url-query-params/Gurl
but this won't work if you pass parameter=your_url_with_character_#_hash, I am passing url as param containing #, and it's not working there.Gurl
Can you give a little explanation too?Shockproof
Thanks for your answer, but using RegExp isn't safe, using query-string would be better.Bicycle
F
17

There is a URL class in JavaScript which is intended to let you both build and parse URLs robustly, making query parameters easily accessible:

const url = new URL('url-app-scheme://somePage?someVar=someVal');
url.searchParams.get('someVar')

Sadly, the implementation of URL in React Native is not complete and has some known bugs. Fortunately, there is a solid polyfill library called react-native-url-polyfill which provides an implementation of URL that is well behaved and tested - I highly recommend it.

Flavoring answered 17/3, 2021 at 23:3 Comment(1)
for me, React Native says "not implemented" when using new URL(...Nerveracking
H
8

Using query-string its working

yarn add  query-string

import queryString from 'query-string';

const parsed = queryString.parseUrl("https://pokeapi.co/api/v2/pokemon?offset=10&limit=10");
console.log(parsed.query.offset) will display 10
Hu answered 23/2, 2021 at 9:7 Comment(0)
O
4

There are ways of doing this that you can leverage from the JS ecosystem. Try URI.js https://github.com/medialize/URI.js

Oystercatcher answered 18/5, 2017 at 10:5 Comment(0)
D
2

I have the same requirement the above solution works for me just to add on with the above answer below worked for me as well

const regex = /[?&]([^=#]+)=([^&#]*)/g;

let params = {},match;

 while ((match = regex.exec(url))) {
   params[match[1]] = match[2];
 }
console.log('parsed params', params);

For example if the input is like below

https://example.com/masterplan/user?auth_token=175032c6210c32833ac70447c3f049cf9126343af9a9399373ff58e87d06479e845f35b93bc6c234ba37a9dec9&userId=1256345&userType=78

Output will be like below

{"auth_token": "175032c6210c32833ac70447c3f049cf9126343af9a9399373ff58e87d06479e845f35b93bc6c234ba37a9dec9", "userId": "1256345", "userType": "95"}

Danforth answered 16/11, 2023 at 7:56 Comment(0)
P
1

Try url https://www.npmjs.com/package/url

"This module has utilities for URL resolution and parsing meant to have feature parity with node.js core url module."

The node URL object is available to your app when using the Chrome react-native debugger, but is not available on your iPhone when untethered.

So use this package

npm install url

Sample code:

import url from 'url';

...

let urlObject = url.parse(inUrlString);
let outUrlString = urlObject.protocol + '//' + urlObject.host + '/more/jump?jump_path=' + encodeURIComponent(urlObject.pathname);
Pozsony answered 12/1, 2018 at 0:14 Comment(1)
Could you please tell me, how can I extract url-params using this module, I seen it's github docs, but could not figure out, for url="example.com/path/?id=1"?Gurl
R
0
url="example.com/path/?id=1"
let urlObject = url.parse(url, true); // second parameter `true` (parse search query)
console.log(urlObject.query['id']); // 1
Reneta answered 24/12, 2020 at 11:29 Comment(1)
Welcome to Stack Overflow! While this code may solve the question, including an explanation of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please edit your answer to add explanations and give an indication of what limitations and assumptions apply.Ladysmith
M
-2

Update: This is not a solution to the above question because it doesn't work unless in debugging mode. I have not deleted this answer however, because I think it points out a note worthy nuance.

JavaScript's very own URL Web API is supported in React Native (using version 0.46). You can use to to parse or build any and every part of the url with great ease.

The API is identical to the WHATWG API of the URL module in Node.js This answer should really be more obvious, but its easy to get lost with the number of okay url parsing packages available.

Edit: This works only in the JS debugging mode for some reason, and not otherwise. So this solution doesn't really hold valid, but I'm leaving it here because I'd love to know how to get the same URL module to work with react-native.

Mating answered 14/7, 2017 at 12:15 Comment(3)
This might be because it is coming from your browser instead of react native. That is too bad :(Vulturine
When you turn on "Remote JS Debugging", your code will run in the browser instead of your device. Chrome uses V8 and RN uses JavaScriptCore so you experience differences like this. You can get more information here: facebook.github.io/react-native/docs/…Plano
@Plano thanks for clarifying the reason behind this behaviour with your comment.Mating

© 2022 - 2024 — McMap. All rights reserved.