diff --git a/src/get-query-string-value.js b/src/get-query-string-value.js new file mode 100644 index 00000000..8fe0fb22 --- /dev/null +++ b/src/get-query-string-value.js @@ -0,0 +1,28 @@ +export default getQueryStringValue + +/** + * Original Source: https://stackoverflow.com/questions/901115/ + * + * This method will return the query string value + * of the given parameter name + * + * @param {String} name - The parameter name in query string + * @param {String} url - The url with query string + * @return {String} - The query string value + */ + +function getQueryStringValue(name, url) { + + name = name.replace(/[\[\]]/g, '\\$&') + const regex = new RegExp(`[?&]${name}(=([^&#]*)|&|#|$)`) + const results = regex.exec(url) + if (!results) { + return null + } + + if (!results[2]) { + return '' + } + + return decodeURIComponent(results[2].replace(/\+/g, ' ')) +} diff --git a/src/index.js b/src/index.js index e4dfeb57..e326dc8c 100644 --- a/src/index.js +++ b/src/index.js @@ -56,6 +56,7 @@ import isPrime from './is-prime' import swapElements from './swapElements' import reverse from './reverse' import removeAccents from './remove-accents' +import getQueryStringValue from './get-query-string-value' export { isOdd, @@ -116,4 +117,5 @@ export { swapElements, reverse, removeAccents, + getQueryStringValue, } diff --git a/test/get-query-string-value.test.js b/test/get-query-string-value.test.js new file mode 100644 index 00000000..385d2763 --- /dev/null +++ b/test/get-query-string-value.test.js @@ -0,0 +1,32 @@ +import test from 'ava' +import {getQueryStringValue} from '../src' + +const url = 'https://www.google.com/search?foo=bar&bar=&apple' + +test('returns query string value of the given parameter', t => { + const name = 'foo' + const expected = 'bar' + const actual = getQueryStringValue(name, url) + t.deepEqual(actual, expected) +}) + +test('returns an empty string if parameter is present with empty value', t => { + const name = 'bar' + const expected = '' + const actual = getQueryStringValue(name, url) + t.deepEqual(actual, expected) +}) + +test('returns an empty string if parameter is present with no value', t => { + const name = 'apple' + const expected = '' + const actual = getQueryStringValue(name, url) + t.deepEqual(actual, expected) +}) + +test('returns null if parameter does not exist', t => { + const name = 'pizza' + const expected = null + const actual = getQueryStringValue(name, url) + t.deepEqual(actual, expected) +})