query string takes off last ')' in url2019 Community Moderator ElectionConvert URL parameters to a JavaScript objectConvert javascript object to URL parametersWhat is the difference between String and string in C#?What is the difference between a URI, a URL and a URN?Encode URL in JavaScript?What is the maximum length of a URL in different browsers?How can I get query string values in JavaScript?How do I make the first letter of a string uppercase in JavaScript?Get the current URL with JavaScript?How to replace all occurrences of a string in JavaScriptHow to check whether a string contains a substring in JavaScript?How to change the URI (URL) for a remote Git repository?
How can I query the supported timezones in Apex?
How to test the sharpness of a knife?
Does the Shadow Magic sorcerer's Eyes of the Dark feature work on all Darkness spells or just his/her own?
Why is this tree refusing to shed its dead leaves?
Did Nintendo change its mind about 68000 SNES?
Would this string work as string?
How do you justify more code being written by following clean code practices?
Are hand made posters acceptable in Academia?
Homology of the fiber
"Marked down as someone wanting to sell shares." What does that mean?
Difficulty understanding group delay concept
Splitting fasta file into smaller files based on header pattern
Don't understand why (5 | -2) > 0 is False where (5 or -2) > 0 is True
Single word to change groups
Is there any common country to visit for uk and schengen visa?
Why is participating in the European Parliamentary elections used as a threat?
Why does Surtur say that Thor is Asgard's doom?
Would storms on an ocean world harm the marine life?
Does convergence of polynomials imply that of its coefficients?
is this saw blade faulty?
Nested Dynamic SOQL Query
Print last inputted byte
What is the tangent at a sharp point on a curve?
Why didn’t Eve recognize the little cockroach as a living organism?
query string takes off last ')' in url
2019 Community Moderator ElectionConvert URL parameters to a JavaScript objectConvert javascript object to URL parametersWhat is the difference between String and string in C#?What is the difference between a URI, a URL and a URN?Encode URL in JavaScript?What is the maximum length of a URL in different browsers?How can I get query string values in JavaScript?How do I make the first letter of a string uppercase in JavaScript?Get the current URL with JavaScript?How to replace all occurrences of a string in JavaScriptHow to check whether a string contains a substring in JavaScript?How to change the URI (URL) for a remote Git repository?
I am constructing a query string in Javascript based on whether a checkbox is checked or not.
Some of the options in the checkboxes are
- "Annual"
- "Grass"
- "Shrub (Evergreen)"
- "Shrub (Deciduous)"
I found a function online that updates the url parameter:
function updateUrlParameter(uri, key, value)
value = value.replace(/s/g, "%20");
var i = uri.indexOf('#');
var hash = i === -1 ? '' : uri.substr(i);
uri = i === -1 ? uri : uri.substr(0, i);
var re = new RegExp("([?&])" + key + "=.*?(&
Using the above function, if I check the checkboxes for the above four starting from top down, my query string becomes
?plantType=Annual&plantType=Grass&plantType=Shrub%20(Evergreen)&plantType=Shrub%20(Deciduous
Why is the function ignoring the last ')' in the string? Is there a work around this? I would like to keep the parenthesis in the query string because this will make querying the database easier.
I created a function to iterate through input checkboxes. If they are checked, then use the updateUrlParameter function to update the URI.
function getQueryString()
var inputsContainerChildren = $('#floatingDivForFilter').children();
var input = document.createElement('input')
var uri = '';
for (var i = 0; i < inputsContainerChildren.length; i++)
var currChild = inputsContainerChildren[i].firstElementChild;
if (currChild)
if (currChild.tagName === 'INPUT')
if (currChild.checked)
var id = currChild.id;
console.log(uri)
uri = updateUrlParameter(uri, currChild.name, currChild.value);
console.log(uri);
The photo below shows a snapshot of the URL produced. I can't figure out why the last ')' is chopped off.
url photo
javascript string url
|
show 4 more comments
I am constructing a query string in Javascript based on whether a checkbox is checked or not.
Some of the options in the checkboxes are
- "Annual"
- "Grass"
- "Shrub (Evergreen)"
- "Shrub (Deciduous)"
I found a function online that updates the url parameter:
function updateUrlParameter(uri, key, value)
value = value.replace(/s/g, "%20");
var i = uri.indexOf('#');
var hash = i === -1 ? '' : uri.substr(i);
uri = i === -1 ? uri : uri.substr(0, i);
var re = new RegExp("([?&])" + key + "=.*?(&
Using the above function, if I check the checkboxes for the above four starting from top down, my query string becomes
?plantType=Annual&plantType=Grass&plantType=Shrub%20(Evergreen)&plantType=Shrub%20(Deciduous
Why is the function ignoring the last ')' in the string? Is there a work around this? I would like to keep the parenthesis in the query string because this will make querying the database easier.
I created a function to iterate through input checkboxes. If they are checked, then use the updateUrlParameter function to update the URI.
function getQueryString()
var inputsContainerChildren = $('#floatingDivForFilter').children();
var input = document.createElement('input')
var uri = '';
for (var i = 0; i < inputsContainerChildren.length; i++)
var currChild = inputsContainerChildren[i].firstElementChild;
if (currChild)
if (currChild.tagName === 'INPUT')
if (currChild.checked)
var id = currChild.id;
console.log(uri)
uri = updateUrlParameter(uri, currChild.name, currChild.value);
console.log(uri);
The photo below shows a snapshot of the URL produced. I can't figure out why the last ')' is chopped off.
url photo
javascript string url
4
I would advise against querying the database with values passed directly in from your query string. That's a great way to open yourself up for SQL injection.
– aridlehoover
Mar 7 at 17:58
3
This seems a little like reinventing the wheel, as submitting a form with method=GET will pretty much do all this for you.
– James
Mar 7 at 18:04
You're over complicating things here, 1 you're using a function you dont understand to do something fairly simple doing other means
– Joe Warner
Mar 7 at 18:06
1
The problem is not in this function. The function works as expected: jsfiddle.net/7d3ofu5w - The problem must be in the code that calls this function or in the HTML markup or in the code that uses the result.
– NineBerry
Mar 7 at 18:19
1
Is you post a Minimal, Complete, and Verifiable example we may be able to help you.
– Barmar
Mar 7 at 18:23
|
show 4 more comments
I am constructing a query string in Javascript based on whether a checkbox is checked or not.
Some of the options in the checkboxes are
- "Annual"
- "Grass"
- "Shrub (Evergreen)"
- "Shrub (Deciduous)"
I found a function online that updates the url parameter:
function updateUrlParameter(uri, key, value)
value = value.replace(/s/g, "%20");
var i = uri.indexOf('#');
var hash = i === -1 ? '' : uri.substr(i);
uri = i === -1 ? uri : uri.substr(0, i);
var re = new RegExp("([?&])" + key + "=.*?(&
Using the above function, if I check the checkboxes for the above four starting from top down, my query string becomes
?plantType=Annual&plantType=Grass&plantType=Shrub%20(Evergreen)&plantType=Shrub%20(Deciduous
Why is the function ignoring the last ')' in the string? Is there a work around this? I would like to keep the parenthesis in the query string because this will make querying the database easier.
I created a function to iterate through input checkboxes. If they are checked, then use the updateUrlParameter function to update the URI.
function getQueryString()
var inputsContainerChildren = $('#floatingDivForFilter').children();
var input = document.createElement('input')
var uri = '';
for (var i = 0; i < inputsContainerChildren.length; i++)
var currChild = inputsContainerChildren[i].firstElementChild;
if (currChild)
if (currChild.tagName === 'INPUT')
if (currChild.checked)
var id = currChild.id;
console.log(uri)
uri = updateUrlParameter(uri, currChild.name, currChild.value);
console.log(uri);
The photo below shows a snapshot of the URL produced. I can't figure out why the last ')' is chopped off.
url photo
javascript string url
I am constructing a query string in Javascript based on whether a checkbox is checked or not.
Some of the options in the checkboxes are
- "Annual"
- "Grass"
- "Shrub (Evergreen)"
- "Shrub (Deciduous)"
I found a function online that updates the url parameter:
function updateUrlParameter(uri, key, value)
value = value.replace(/s/g, "%20");
var i = uri.indexOf('#');
var hash = i === -1 ? '' : uri.substr(i);
uri = i === -1 ? uri : uri.substr(0, i);
var re = new RegExp("([?&])" + key + "=.*?(&
Using the above function, if I check the checkboxes for the above four starting from top down, my query string becomes
?plantType=Annual&plantType=Grass&plantType=Shrub%20(Evergreen)&plantType=Shrub%20(Deciduous
Why is the function ignoring the last ')' in the string? Is there a work around this? I would like to keep the parenthesis in the query string because this will make querying the database easier.
I created a function to iterate through input checkboxes. If they are checked, then use the updateUrlParameter function to update the URI.
function getQueryString()
var inputsContainerChildren = $('#floatingDivForFilter').children();
var input = document.createElement('input')
var uri = '';
for (var i = 0; i < inputsContainerChildren.length; i++)
var currChild = inputsContainerChildren[i].firstElementChild;
if (currChild)
if (currChild.tagName === 'INPUT')
if (currChild.checked)
var id = currChild.id;
console.log(uri)
uri = updateUrlParameter(uri, currChild.name, currChild.value);
console.log(uri);
The photo below shows a snapshot of the URL produced. I can't figure out why the last ')' is chopped off.
url photo
javascript string url
javascript string url
edited Mar 7 at 18:32
hello
asked Mar 7 at 17:55
hellohello
33
33
4
I would advise against querying the database with values passed directly in from your query string. That's a great way to open yourself up for SQL injection.
– aridlehoover
Mar 7 at 17:58
3
This seems a little like reinventing the wheel, as submitting a form with method=GET will pretty much do all this for you.
– James
Mar 7 at 18:04
You're over complicating things here, 1 you're using a function you dont understand to do something fairly simple doing other means
– Joe Warner
Mar 7 at 18:06
1
The problem is not in this function. The function works as expected: jsfiddle.net/7d3ofu5w - The problem must be in the code that calls this function or in the HTML markup or in the code that uses the result.
– NineBerry
Mar 7 at 18:19
1
Is you post a Minimal, Complete, and Verifiable example we may be able to help you.
– Barmar
Mar 7 at 18:23
|
show 4 more comments
4
I would advise against querying the database with values passed directly in from your query string. That's a great way to open yourself up for SQL injection.
– aridlehoover
Mar 7 at 17:58
3
This seems a little like reinventing the wheel, as submitting a form with method=GET will pretty much do all this for you.
– James
Mar 7 at 18:04
You're over complicating things here, 1 you're using a function you dont understand to do something fairly simple doing other means
– Joe Warner
Mar 7 at 18:06
1
The problem is not in this function. The function works as expected: jsfiddle.net/7d3ofu5w - The problem must be in the code that calls this function or in the HTML markup or in the code that uses the result.
– NineBerry
Mar 7 at 18:19
1
Is you post a Minimal, Complete, and Verifiable example we may be able to help you.
– Barmar
Mar 7 at 18:23
4
4
I would advise against querying the database with values passed directly in from your query string. That's a great way to open yourself up for SQL injection.
– aridlehoover
Mar 7 at 17:58
I would advise against querying the database with values passed directly in from your query string. That's a great way to open yourself up for SQL injection.
– aridlehoover
Mar 7 at 17:58
3
3
This seems a little like reinventing the wheel, as submitting a form with method=GET will pretty much do all this for you.
– James
Mar 7 at 18:04
This seems a little like reinventing the wheel, as submitting a form with method=GET will pretty much do all this for you.
– James
Mar 7 at 18:04
You're over complicating things here, 1 you're using a function you dont understand to do something fairly simple doing other means
– Joe Warner
Mar 7 at 18:06
You're over complicating things here, 1 you're using a function you dont understand to do something fairly simple doing other means
– Joe Warner
Mar 7 at 18:06
1
1
The problem is not in this function. The function works as expected: jsfiddle.net/7d3ofu5w - The problem must be in the code that calls this function or in the HTML markup or in the code that uses the result.
– NineBerry
Mar 7 at 18:19
The problem is not in this function. The function works as expected: jsfiddle.net/7d3ofu5w - The problem must be in the code that calls this function or in the HTML markup or in the code that uses the result.
– NineBerry
Mar 7 at 18:19
1
1
Is you post a Minimal, Complete, and Verifiable example we may be able to help you.
– Barmar
Mar 7 at 18:23
Is you post a Minimal, Complete, and Verifiable example we may be able to help you.
– Barmar
Mar 7 at 18:23
|
show 4 more comments
2 Answers
2
active
oldest
votes
The issue you are seeing is just the Chrome developer tools trying to be too clever.
When logging the url to the console, Chrome will not recognize the full url as a link but exclude the closing ")". They probably do that because it will be very common that people write an url in braces and it is not expected that the closing brace is part of the url.
Since this is only an issue of the developer tools, you can ignore the issue. It will not affect the runtime behaviour of your code.
The issue will be solved when you correctly escape special characters in the parameters (as you should do anyway):
function updateUrlParameter(uri, key, value)
// removed because escape will do that
// value = value.replace(/s/g, "%20");
var i = uri.indexOf('#');
var hash = i === -1 ? '' : uri.substr(i);
uri = i === -1 ? uri : uri.substr(0, i);
var separator = uri.indexOf('?') !== -1 ? "&" : "?";
if (!value)
// remove key-value pair if value is empty
uri = uri.replace(new RegExp("([&]?)" + key + "=.*?(& else
console.log("value is " + value)
// Use escape on key and value
uri = uri + separator + escape(key) + "=" + escape(value);
return uri + hash;
let s = "http://chrome.is.too.clever/";
s = updateUrlParameter(s, "plantType", "Annual");
s = updateUrlParameter(s, "plantType", "Grass");
s = updateUrlParameter(s, "plantType", "Shrub (Evergreen)");
s = updateUrlParameter(s, "plantType", "Shrub (Deciduous)");
console.log(s);
Fiddle
Thank you for your explanation. I was wondering for the longest time why it excluded the last ')'.
– hello
Mar 7 at 19:10
add a comment |
Instead of using a regular expression, just convert the params to an object, modify said object, and convert it back into params.
var url = 'https://x.y?plantType=Annual&plantType=Grass&plantType=Shrub%20(Evergreen)&plantType=Shrub%20(Deciduous)';
function updateUrlParameter(uri, key, value)
let url = new URL(uri), object = deserializeQuery(url.search); // params to obj
object[key] = value; // modify obj
return url.origin + '?' + serializeQuery(object); // obj to url + params
console.log(updateUrlParameter(url, 'plantType', [ 'Pine', 'Palm', 'Rose (Red)' ]));
/** ======= Serialization / Deserialization functions below ======== */
// https://stackoverflow.com/a/47517503/1762224
function deserializeQuery(queryString, queryKey)
let query = , pairs = (queryString[0] === '?' ? queryString.substr(1) : queryString).split('&');
for (var i = 0; i < pairs.length; i++) '');
value = (value.indexOf(',') === -1 ? value : value.split(','));
query[key] = query[key] ? (query[key].constructor === Array ? query[key].concat(value) : [query[key], value]) : value;
return typeof queryKey === 'undefined' ? query : query[queryKey];
// https://stackoverflow.com/a/53528203/1762224
function serializeQuery(params, keys = [], isArray = false)
const p = Object.keys(params).map(key => Array.isArray(val))
keys.push(Array.isArray(params) ? "" : key);
return serializeQuery(val, keys, Array.isArray(val));
else
let tKey = keys.length > 0 ? ((isArray ? keys : [...keys, key]).reduce((str, k) => "" === str ? k : `$str[$k]`, "")) : key;
if (isArray)
return encodeURIComponent(tKey) + '=' + encodeURIComponent(val);
).join('&');
keys.pop();
return p;
.as-console-wrapper
top: 0;
max-height: 100% !important;
.as-console-row
white-space: pre-wrap;
word-break: break-all;
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55050091%2fquery-string-takes-off-last-in-url%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
The issue you are seeing is just the Chrome developer tools trying to be too clever.
When logging the url to the console, Chrome will not recognize the full url as a link but exclude the closing ")". They probably do that because it will be very common that people write an url in braces and it is not expected that the closing brace is part of the url.
Since this is only an issue of the developer tools, you can ignore the issue. It will not affect the runtime behaviour of your code.
The issue will be solved when you correctly escape special characters in the parameters (as you should do anyway):
function updateUrlParameter(uri, key, value)
// removed because escape will do that
// value = value.replace(/s/g, "%20");
var i = uri.indexOf('#');
var hash = i === -1 ? '' : uri.substr(i);
uri = i === -1 ? uri : uri.substr(0, i);
var separator = uri.indexOf('?') !== -1 ? "&" : "?";
if (!value)
// remove key-value pair if value is empty
uri = uri.replace(new RegExp("([&]?)" + key + "=.*?(& else
console.log("value is " + value)
// Use escape on key and value
uri = uri + separator + escape(key) + "=" + escape(value);
return uri + hash;
let s = "http://chrome.is.too.clever/";
s = updateUrlParameter(s, "plantType", "Annual");
s = updateUrlParameter(s, "plantType", "Grass");
s = updateUrlParameter(s, "plantType", "Shrub (Evergreen)");
s = updateUrlParameter(s, "plantType", "Shrub (Deciduous)");
console.log(s);
Fiddle
Thank you for your explanation. I was wondering for the longest time why it excluded the last ')'.
– hello
Mar 7 at 19:10
add a comment |
The issue you are seeing is just the Chrome developer tools trying to be too clever.
When logging the url to the console, Chrome will not recognize the full url as a link but exclude the closing ")". They probably do that because it will be very common that people write an url in braces and it is not expected that the closing brace is part of the url.
Since this is only an issue of the developer tools, you can ignore the issue. It will not affect the runtime behaviour of your code.
The issue will be solved when you correctly escape special characters in the parameters (as you should do anyway):
function updateUrlParameter(uri, key, value)
// removed because escape will do that
// value = value.replace(/s/g, "%20");
var i = uri.indexOf('#');
var hash = i === -1 ? '' : uri.substr(i);
uri = i === -1 ? uri : uri.substr(0, i);
var separator = uri.indexOf('?') !== -1 ? "&" : "?";
if (!value)
// remove key-value pair if value is empty
uri = uri.replace(new RegExp("([&]?)" + key + "=.*?(& else
console.log("value is " + value)
// Use escape on key and value
uri = uri + separator + escape(key) + "=" + escape(value);
return uri + hash;
let s = "http://chrome.is.too.clever/";
s = updateUrlParameter(s, "plantType", "Annual");
s = updateUrlParameter(s, "plantType", "Grass");
s = updateUrlParameter(s, "plantType", "Shrub (Evergreen)");
s = updateUrlParameter(s, "plantType", "Shrub (Deciduous)");
console.log(s);
Fiddle
Thank you for your explanation. I was wondering for the longest time why it excluded the last ')'.
– hello
Mar 7 at 19:10
add a comment |
The issue you are seeing is just the Chrome developer tools trying to be too clever.
When logging the url to the console, Chrome will not recognize the full url as a link but exclude the closing ")". They probably do that because it will be very common that people write an url in braces and it is not expected that the closing brace is part of the url.
Since this is only an issue of the developer tools, you can ignore the issue. It will not affect the runtime behaviour of your code.
The issue will be solved when you correctly escape special characters in the parameters (as you should do anyway):
function updateUrlParameter(uri, key, value)
// removed because escape will do that
// value = value.replace(/s/g, "%20");
var i = uri.indexOf('#');
var hash = i === -1 ? '' : uri.substr(i);
uri = i === -1 ? uri : uri.substr(0, i);
var separator = uri.indexOf('?') !== -1 ? "&" : "?";
if (!value)
// remove key-value pair if value is empty
uri = uri.replace(new RegExp("([&]?)" + key + "=.*?(& else
console.log("value is " + value)
// Use escape on key and value
uri = uri + separator + escape(key) + "=" + escape(value);
return uri + hash;
let s = "http://chrome.is.too.clever/";
s = updateUrlParameter(s, "plantType", "Annual");
s = updateUrlParameter(s, "plantType", "Grass");
s = updateUrlParameter(s, "plantType", "Shrub (Evergreen)");
s = updateUrlParameter(s, "plantType", "Shrub (Deciduous)");
console.log(s);
Fiddle
The issue you are seeing is just the Chrome developer tools trying to be too clever.
When logging the url to the console, Chrome will not recognize the full url as a link but exclude the closing ")". They probably do that because it will be very common that people write an url in braces and it is not expected that the closing brace is part of the url.
Since this is only an issue of the developer tools, you can ignore the issue. It will not affect the runtime behaviour of your code.
The issue will be solved when you correctly escape special characters in the parameters (as you should do anyway):
function updateUrlParameter(uri, key, value)
// removed because escape will do that
// value = value.replace(/s/g, "%20");
var i = uri.indexOf('#');
var hash = i === -1 ? '' : uri.substr(i);
uri = i === -1 ? uri : uri.substr(0, i);
var separator = uri.indexOf('?') !== -1 ? "&" : "?";
if (!value)
// remove key-value pair if value is empty
uri = uri.replace(new RegExp("([&]?)" + key + "=.*?(& else
console.log("value is " + value)
// Use escape on key and value
uri = uri + separator + escape(key) + "=" + escape(value);
return uri + hash;
let s = "http://chrome.is.too.clever/";
s = updateUrlParameter(s, "plantType", "Annual");
s = updateUrlParameter(s, "plantType", "Grass");
s = updateUrlParameter(s, "plantType", "Shrub (Evergreen)");
s = updateUrlParameter(s, "plantType", "Shrub (Deciduous)");
console.log(s);
Fiddle
edited Mar 7 at 18:49
answered Mar 7 at 18:37
NineBerryNineBerry
14.5k23363
14.5k23363
Thank you for your explanation. I was wondering for the longest time why it excluded the last ')'.
– hello
Mar 7 at 19:10
add a comment |
Thank you for your explanation. I was wondering for the longest time why it excluded the last ')'.
– hello
Mar 7 at 19:10
Thank you for your explanation. I was wondering for the longest time why it excluded the last ')'.
– hello
Mar 7 at 19:10
Thank you for your explanation. I was wondering for the longest time why it excluded the last ')'.
– hello
Mar 7 at 19:10
add a comment |
Instead of using a regular expression, just convert the params to an object, modify said object, and convert it back into params.
var url = 'https://x.y?plantType=Annual&plantType=Grass&plantType=Shrub%20(Evergreen)&plantType=Shrub%20(Deciduous)';
function updateUrlParameter(uri, key, value)
let url = new URL(uri), object = deserializeQuery(url.search); // params to obj
object[key] = value; // modify obj
return url.origin + '?' + serializeQuery(object); // obj to url + params
console.log(updateUrlParameter(url, 'plantType', [ 'Pine', 'Palm', 'Rose (Red)' ]));
/** ======= Serialization / Deserialization functions below ======== */
// https://stackoverflow.com/a/47517503/1762224
function deserializeQuery(queryString, queryKey)
let query = , pairs = (queryString[0] === '?' ? queryString.substr(1) : queryString).split('&');
for (var i = 0; i < pairs.length; i++) '');
value = (value.indexOf(',') === -1 ? value : value.split(','));
query[key] = query[key] ? (query[key].constructor === Array ? query[key].concat(value) : [query[key], value]) : value;
return typeof queryKey === 'undefined' ? query : query[queryKey];
// https://stackoverflow.com/a/53528203/1762224
function serializeQuery(params, keys = [], isArray = false)
const p = Object.keys(params).map(key => Array.isArray(val))
keys.push(Array.isArray(params) ? "" : key);
return serializeQuery(val, keys, Array.isArray(val));
else
let tKey = keys.length > 0 ? ((isArray ? keys : [...keys, key]).reduce((str, k) => "" === str ? k : `$str[$k]`, "")) : key;
if (isArray)
return encodeURIComponent(tKey) + '=' + encodeURIComponent(val);
).join('&');
keys.pop();
return p;
.as-console-wrapper
top: 0;
max-height: 100% !important;
.as-console-row
white-space: pre-wrap;
word-break: break-all;
add a comment |
Instead of using a regular expression, just convert the params to an object, modify said object, and convert it back into params.
var url = 'https://x.y?plantType=Annual&plantType=Grass&plantType=Shrub%20(Evergreen)&plantType=Shrub%20(Deciduous)';
function updateUrlParameter(uri, key, value)
let url = new URL(uri), object = deserializeQuery(url.search); // params to obj
object[key] = value; // modify obj
return url.origin + '?' + serializeQuery(object); // obj to url + params
console.log(updateUrlParameter(url, 'plantType', [ 'Pine', 'Palm', 'Rose (Red)' ]));
/** ======= Serialization / Deserialization functions below ======== */
// https://stackoverflow.com/a/47517503/1762224
function deserializeQuery(queryString, queryKey)
let query = , pairs = (queryString[0] === '?' ? queryString.substr(1) : queryString).split('&');
for (var i = 0; i < pairs.length; i++) '');
value = (value.indexOf(',') === -1 ? value : value.split(','));
query[key] = query[key] ? (query[key].constructor === Array ? query[key].concat(value) : [query[key], value]) : value;
return typeof queryKey === 'undefined' ? query : query[queryKey];
// https://stackoverflow.com/a/53528203/1762224
function serializeQuery(params, keys = [], isArray = false)
const p = Object.keys(params).map(key => Array.isArray(val))
keys.push(Array.isArray(params) ? "" : key);
return serializeQuery(val, keys, Array.isArray(val));
else
let tKey = keys.length > 0 ? ((isArray ? keys : [...keys, key]).reduce((str, k) => "" === str ? k : `$str[$k]`, "")) : key;
if (isArray)
return encodeURIComponent(tKey) + '=' + encodeURIComponent(val);
).join('&');
keys.pop();
return p;
.as-console-wrapper
top: 0;
max-height: 100% !important;
.as-console-row
white-space: pre-wrap;
word-break: break-all;
add a comment |
Instead of using a regular expression, just convert the params to an object, modify said object, and convert it back into params.
var url = 'https://x.y?plantType=Annual&plantType=Grass&plantType=Shrub%20(Evergreen)&plantType=Shrub%20(Deciduous)';
function updateUrlParameter(uri, key, value)
let url = new URL(uri), object = deserializeQuery(url.search); // params to obj
object[key] = value; // modify obj
return url.origin + '?' + serializeQuery(object); // obj to url + params
console.log(updateUrlParameter(url, 'plantType', [ 'Pine', 'Palm', 'Rose (Red)' ]));
/** ======= Serialization / Deserialization functions below ======== */
// https://stackoverflow.com/a/47517503/1762224
function deserializeQuery(queryString, queryKey)
let query = , pairs = (queryString[0] === '?' ? queryString.substr(1) : queryString).split('&');
for (var i = 0; i < pairs.length; i++) '');
value = (value.indexOf(',') === -1 ? value : value.split(','));
query[key] = query[key] ? (query[key].constructor === Array ? query[key].concat(value) : [query[key], value]) : value;
return typeof queryKey === 'undefined' ? query : query[queryKey];
// https://stackoverflow.com/a/53528203/1762224
function serializeQuery(params, keys = [], isArray = false)
const p = Object.keys(params).map(key => Array.isArray(val))
keys.push(Array.isArray(params) ? "" : key);
return serializeQuery(val, keys, Array.isArray(val));
else
let tKey = keys.length > 0 ? ((isArray ? keys : [...keys, key]).reduce((str, k) => "" === str ? k : `$str[$k]`, "")) : key;
if (isArray)
return encodeURIComponent(tKey) + '=' + encodeURIComponent(val);
).join('&');
keys.pop();
return p;
.as-console-wrapper
top: 0;
max-height: 100% !important;
.as-console-row
white-space: pre-wrap;
word-break: break-all;
Instead of using a regular expression, just convert the params to an object, modify said object, and convert it back into params.
var url = 'https://x.y?plantType=Annual&plantType=Grass&plantType=Shrub%20(Evergreen)&plantType=Shrub%20(Deciduous)';
function updateUrlParameter(uri, key, value)
let url = new URL(uri), object = deserializeQuery(url.search); // params to obj
object[key] = value; // modify obj
return url.origin + '?' + serializeQuery(object); // obj to url + params
console.log(updateUrlParameter(url, 'plantType', [ 'Pine', 'Palm', 'Rose (Red)' ]));
/** ======= Serialization / Deserialization functions below ======== */
// https://stackoverflow.com/a/47517503/1762224
function deserializeQuery(queryString, queryKey)
let query = , pairs = (queryString[0] === '?' ? queryString.substr(1) : queryString).split('&');
for (var i = 0; i < pairs.length; i++) '');
value = (value.indexOf(',') === -1 ? value : value.split(','));
query[key] = query[key] ? (query[key].constructor === Array ? query[key].concat(value) : [query[key], value]) : value;
return typeof queryKey === 'undefined' ? query : query[queryKey];
// https://stackoverflow.com/a/53528203/1762224
function serializeQuery(params, keys = [], isArray = false)
const p = Object.keys(params).map(key => Array.isArray(val))
keys.push(Array.isArray(params) ? "" : key);
return serializeQuery(val, keys, Array.isArray(val));
else
let tKey = keys.length > 0 ? ((isArray ? keys : [...keys, key]).reduce((str, k) => "" === str ? k : `$str[$k]`, "")) : key;
if (isArray)
return encodeURIComponent(tKey) + '=' + encodeURIComponent(val);
).join('&');
keys.pop();
return p;
.as-console-wrapper
top: 0;
max-height: 100% !important;
.as-console-row
white-space: pre-wrap;
word-break: break-all;
var url = 'https://x.y?plantType=Annual&plantType=Grass&plantType=Shrub%20(Evergreen)&plantType=Shrub%20(Deciduous)';
function updateUrlParameter(uri, key, value)
let url = new URL(uri), object = deserializeQuery(url.search); // params to obj
object[key] = value; // modify obj
return url.origin + '?' + serializeQuery(object); // obj to url + params
console.log(updateUrlParameter(url, 'plantType', [ 'Pine', 'Palm', 'Rose (Red)' ]));
/** ======= Serialization / Deserialization functions below ======== */
// https://stackoverflow.com/a/47517503/1762224
function deserializeQuery(queryString, queryKey)
let query = , pairs = (queryString[0] === '?' ? queryString.substr(1) : queryString).split('&');
for (var i = 0; i < pairs.length; i++) '');
value = (value.indexOf(',') === -1 ? value : value.split(','));
query[key] = query[key] ? (query[key].constructor === Array ? query[key].concat(value) : [query[key], value]) : value;
return typeof queryKey === 'undefined' ? query : query[queryKey];
// https://stackoverflow.com/a/53528203/1762224
function serializeQuery(params, keys = [], isArray = false)
const p = Object.keys(params).map(key => Array.isArray(val))
keys.push(Array.isArray(params) ? "" : key);
return serializeQuery(val, keys, Array.isArray(val));
else
let tKey = keys.length > 0 ? ((isArray ? keys : [...keys, key]).reduce((str, k) => "" === str ? k : `$str[$k]`, "")) : key;
if (isArray)
return encodeURIComponent(tKey) + '=' + encodeURIComponent(val);
).join('&');
keys.pop();
return p;
.as-console-wrapper
top: 0;
max-height: 100% !important;
.as-console-row
white-space: pre-wrap;
word-break: break-all;
var url = 'https://x.y?plantType=Annual&plantType=Grass&plantType=Shrub%20(Evergreen)&plantType=Shrub%20(Deciduous)';
function updateUrlParameter(uri, key, value)
let url = new URL(uri), object = deserializeQuery(url.search); // params to obj
object[key] = value; // modify obj
return url.origin + '?' + serializeQuery(object); // obj to url + params
console.log(updateUrlParameter(url, 'plantType', [ 'Pine', 'Palm', 'Rose (Red)' ]));
/** ======= Serialization / Deserialization functions below ======== */
// https://stackoverflow.com/a/47517503/1762224
function deserializeQuery(queryString, queryKey)
let query = , pairs = (queryString[0] === '?' ? queryString.substr(1) : queryString).split('&');
for (var i = 0; i < pairs.length; i++) '');
value = (value.indexOf(',') === -1 ? value : value.split(','));
query[key] = query[key] ? (query[key].constructor === Array ? query[key].concat(value) : [query[key], value]) : value;
return typeof queryKey === 'undefined' ? query : query[queryKey];
// https://stackoverflow.com/a/53528203/1762224
function serializeQuery(params, keys = [], isArray = false)
const p = Object.keys(params).map(key => Array.isArray(val))
keys.push(Array.isArray(params) ? "" : key);
return serializeQuery(val, keys, Array.isArray(val));
else
let tKey = keys.length > 0 ? ((isArray ? keys : [...keys, key]).reduce((str, k) => "" === str ? k : `$str[$k]`, "")) : key;
if (isArray)
return encodeURIComponent(tKey) + '=' + encodeURIComponent(val);
).join('&');
keys.pop();
return p;
.as-console-wrapper
top: 0;
max-height: 100% !important;
.as-console-row
white-space: pre-wrap;
word-break: break-all;
answered Mar 7 at 18:50
Mr. PolywhirlMr. Polywhirl
17.5k84992
17.5k84992
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55050091%2fquery-string-takes-off-last-in-url%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
4
I would advise against querying the database with values passed directly in from your query string. That's a great way to open yourself up for SQL injection.
– aridlehoover
Mar 7 at 17:58
3
This seems a little like reinventing the wheel, as submitting a form with method=GET will pretty much do all this for you.
– James
Mar 7 at 18:04
You're over complicating things here, 1 you're using a function you dont understand to do something fairly simple doing other means
– Joe Warner
Mar 7 at 18:06
1
The problem is not in this function. The function works as expected: jsfiddle.net/7d3ofu5w - The problem must be in the code that calls this function or in the HTML markup or in the code that uses the result.
– NineBerry
Mar 7 at 18:19
1
Is you post a Minimal, Complete, and Verifiable example we may be able to help you.
– Barmar
Mar 7 at 18:23