Skip to content

Instantly share code, notes, and snippets.

@mirinzhang
Last active September 7, 2018 10:49
Show Gist options
  • Save mirinzhang/d5ff635524eb3ba74a80edfe91287d64 to your computer and use it in GitHub Desktop.
Save mirinzhang/d5ff635524eb3ba74a80edfe91287d64 to your computer and use it in GitHub Desktop.
~ Parse a query string into an object and get a query param by name
const urlQuery = {
getAll(url) {
if(!url) {
return {};
}
const regx = /([^?=&]+)=([^&]*)?/g,
result = {};
url.replace(regx, (_, $1, $2) => result[$1] = decodeURIComponent($2 || ''));
return result;
},
getByName(url, name) {
if(!url) {
return null;
}
const result = url.match(new RegExp('(\\?|&)' + name + '=(.*?)(&|$)', 'i')),
param = (result && decodeURIComponent(result[2])) || null;
return param;
}
};
// Usage
const url = 'https://www.google.rs/search?q=react-native&oq=react-native&aqs=chrome..69i57j69i60l3j69i59l2.7340j0j1&sourceid=chrome&ie=UTF-8';
console.log(urlQuery.getAll(url)); // {q: "react-native", oq: "react-native", aqs: "chrome..69i57j69i60l3j69i59l2.7340j0j1", sourceid: "chrome", ie: "UTF-8"}
console.log(urlQuery.getByName(url, 'q')); // react-native
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment