Javascript Function Append Url with Search Query
Javascript Function Append Url with Search Query Making Sure to Not Included Question Mark ? if it Already Exists in the Search Query
Home
Short:
/*-------------------------------------------------------------- Append a URL with ?key=value, ensuring subsequent queries use &, not ?, to avoid duplicates like ?key=value?key2=value2. but instead ?val=somevalue&val1=somevalue2 ------------------------------------------------------------- */ function appendQueryParam(url, param, value) { // Check if the URL already contains a '?' (indicating query parameters exist) if (url.includes("?")) { // if so, append the new parameter using '&' return url + "&" + encodeURIComponent(param) + "=" + encodeURIComponent(value); } else { // otherwise, append it using '?' to start the query string return url + "?" + encodeURIComponent(param) + "=" + encodeURIComponent(value); } }
source code home