Skip to content
This repository was archived by the owner on Feb 20, 2019. It is now read-only.

Commit 3dc204a

Browse files
author
Kent C. Dodds
committed
feat(getQueryStringParam): Add getQueryStringParam function
1 parent 6cb53b5 commit 3dc204a

File tree

3 files changed

+42
-1
lines changed

3 files changed

+42
-1
lines changed

src/get-query-string-param.js

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
export default getQueryStringParam
2+
3+
/**
4+
* Original Source: http://stackoverflow.com/a/901144/971592
5+
*
6+
* This method will get the value of a part of a query string in a given url
7+
*
8+
* @param {String} url - the url to get the value from
9+
* @param {String} name - The property from the query string
10+
* @return {String} - the value
11+
*/
12+
function getQueryStringParam(url, name) {
13+
const regexReadyName = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]')
14+
const regex = new RegExp('[\\?&]' + regexReadyName + '=([^&#]*)')
15+
const results = regex.exec(url)
16+
return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '))
17+
}
18+

src/index.js

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,9 @@
11
import flatten from './flatten'
2+
import getQueryStringParam from './get-query-string-param'
23
import snakeToCamel from './snake-to-camel'
34

4-
export {flatten, snakeToCamel}
5+
export {
6+
flatten,
7+
snakeToCamel,
8+
getQueryStringParam,
9+
}

test/get-query-string-param.test.js

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
import test from 'ava'
2+
import {getQueryStringParam} from '../src'
3+
4+
const url = 'https://egghead.io/?utm_source=test&utm_medium=code&utm_campaign=contributing-to-open-source'
5+
6+
test('gets the given parameter', t => {
7+
const name = 'utm_campaign'
8+
const expected = 'contributing-to-open-source'
9+
const actual = getQueryStringParam(url, name)
10+
t.same(actual, expected)
11+
})
12+
13+
test('returns an empty string if param does not exist', t => {
14+
const name = 'missing-thing'
15+
const expected = ''
16+
const actual = getQueryStringParam(url, name)
17+
t.same(actual, expected)
18+
})

0 commit comments

Comments
 (0)