Last active
September 7, 2018 10:49
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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