Last active
December 17, 2015 23:29
-
-
Save aniketpant/5689310 to your computer and use it in GitHub Desktop.
Query String Problem
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
// Implode/Explode Approach | |
function queryString (str, param, value) { | |
var output = ""; | |
splitString = str.split('?'); | |
baseURL = splitString[0]; | |
params = splitString[1].split('&'); | |
ctr = 0; | |
params.forEach(function(p) { | |
if (p.split('=')[0] == param) { | |
p = param + '=' + value; | |
} | |
else { | |
ctr++; | |
} | |
}); | |
if (ctr == params.length) | |
params.push(param + '=' + value); | |
output = baseURL + '?' + params.join("&"); | |
return output; | |
} | |
console.log(queryString("http://aniketpant.com/abc?a=1&b=2", 'c', '10')); | |
console.log(queryString("http://aniketpant.com/abc?a=1&b=2&c=25", 'c', '10')); |
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
// Regex Approach | |
function queryString (str, param, value) { | |
var output = ""; | |
var regex = /http\:\/\/aniketpant\.com\/abc\?(\S+)/; | |
var params = regex.exec(str)[1]; // list of paramenter | |
return params; | |
} | |
console.log(queryString("http://aniketpant.com/abc?a=1&b=2", 'c', '10')); | |
console.log(queryString("http://aniketpant.com/abc?a=1&b=2&c=25", 'c', '10')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment