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

Commit ac7c97d

Browse files
dominictwleeKent C. Dodds
authored and
Kent C. Dodds
committed
feat(get-query-string-value): add new method
* WIP: Cannot get coverage quite there * fix(compile): achieved 100% test coverage
1 parent 700a007 commit ac7c97d

File tree

3 files changed

+62
-0
lines changed

3 files changed

+62
-0
lines changed

src/get-query-string-value.js

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
export default getQueryStringValue
2+
3+
/**
4+
* Original Source: https://stackoverflow.com/questions/901115/
5+
*
6+
* This method will return the query string value
7+
* of the given parameter name
8+
*
9+
* @param {String} name - The parameter name in query string
10+
* @param {String} url - The url with query string
11+
* @return {String} - The query string value
12+
*/
13+
14+
function getQueryStringValue(name, url) {
15+
16+
name = name.replace(/[\[\]]/g, '\\$&')
17+
const regex = new RegExp(`[?&]${name}(=([^&#]*)|&|#|$)`)
18+
const results = regex.exec(url)
19+
if (!results) {
20+
return null
21+
}
22+
23+
if (!results[2]) {
24+
return ''
25+
}
26+
27+
return decodeURIComponent(results[2].replace(/\+/g, ' '))
28+
}

src/index.js

+2
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,7 @@ import isPrime from './is-prime'
5656
import swapElements from './swapElements'
5757
import reverse from './reverse'
5858
import removeAccents from './remove-accents'
59+
import getQueryStringValue from './get-query-string-value'
5960

6061
export {
6162
isOdd,
@@ -116,4 +117,5 @@ export {
116117
swapElements,
117118
reverse,
118119
removeAccents,
120+
getQueryStringValue,
119121
}

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

+32
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
import test from 'ava'
2+
import {getQueryStringValue} from '../src'
3+
4+
const url = 'https://www.google.com/search?foo=bar&bar=&apple'
5+
6+
test('returns query string value of the given parameter', t => {
7+
const name = 'foo'
8+
const expected = 'bar'
9+
const actual = getQueryStringValue(name, url)
10+
t.deepEqual(actual, expected)
11+
})
12+
13+
test('returns an empty string if parameter is present with empty value', t => {
14+
const name = 'bar'
15+
const expected = ''
16+
const actual = getQueryStringValue(name, url)
17+
t.deepEqual(actual, expected)
18+
})
19+
20+
test('returns an empty string if parameter is present with no value', t => {
21+
const name = 'apple'
22+
const expected = ''
23+
const actual = getQueryStringValue(name, url)
24+
t.deepEqual(actual, expected)
25+
})
26+
27+
test('returns null if parameter does not exist', t => {
28+
const name = 'pizza'
29+
const expected = null
30+
const actual = getQueryStringValue(name, url)
31+
t.deepEqual(actual, expected)
32+
})

0 commit comments

Comments
 (0)