Iterate over a URL and add/replace string if needed - javascript

I have an eCommerce Shopify URL that I need to check for a particular string to determine to change the currency or not.
When the user lands on the site, the URL is e.g. https://www.myshop.com.
In the navigation bar, there are buttons that allow the user to change from the default USD currency to their local currency.
This is a native Shopify feature that requires you to add ?currency=GBP (for example to British Pounds) to the URL.
I check if the string ?currency= exists, and if it does it means the user has selected a currency already, but want to change it again. So I strip out 13 characters from the start of the ? and then replace it with the new currency string.
The problem is if someone lands on the site from an ad, the URL might look like https://www.myshop.com?HkuhJKh6876MJ.
Then I have to change the currency URL to & instead of ?
I can iterate over the string and check for more than 1 ? and then change the URL, but it seems long-winded. Is there a better way to do this?
Below is my current code to check for the ?currency= substring and remove and replace it if it exists with a new currency.
<input type="button" value="Show USD" onclick="showUSD()">
<input type="button" value="Show GBP" onclick="showAUD()">
<script>
function showUSD() {
var changeToCurrency = "USD"; // Set selected currency
checkForSubstring(changeToCurrency); // Check for '?currency=' substring
}
function showGBP() {
var changeToCurrency = "GBP";
checkForSubstring(changeToCurrency);
}
// Check for substring
function checkForSubstring (newCurrency) {
var urlString = window.location.href + "";
var currencySubstring = "?currency=";
if ((urlString.includes(currencySubstring))) {
sliceURL(urlString, currencySubstring, newCurrency);
}
else {
alert("Doesnt contain substring. \nLoading new URL.");
window.location.replace(urlString + currencySubstring + newCurrency);
}
}
// Slice URL
function sliceURL (originalURL, stringToSlice, currency) {
var n = originalURL.indexOf(stringToSlice); // Get position of substring
// Slice substring from URL
var S = originalURL + "";
var bindex = n;
var eindex = n + 13;
S = S.substr(0, bindex) + S.substr(eindex);
// Reload new URL
reloadURL(S, stringToSlice, currency);
}
// Reload URL
function reloadURL(baseURL, stc, currency) {
window.location.replace(baseURL + stc + currency);
}
</script>

The method below will replace the currency value in the query string if there is currency present in window.location.search
let updateCurrency = (CUR)=>{
let queryString = window.location.search;
if(queryString && queryString.length){
queryString = queryString.slice(1);
queryStringData = queryString.split("&");
queryStringData.forEach((query,index)=>{
query = query.split("=")
if(query[0]== 'currency'){
queryStringData.splice(index,1);
queryStringData = queryStringData.join('&')
window.location.search =queryStringData +'&currency='+CUR
}
});
}
}

Related

How do I pass multiple variables as query string parameter

I am working with the below Javascript function. It only works when the value is a number. I mean it only returns the value if it is a a number. For example:
var ldInstID = getParameterByName("ID")
If ID is a number then it works and assigns the value to the variable but if the ID is a string it is not working. Please help to make this work for a string too.
I am using this on SharePoint list edit page where ID is a list column value. I want to capture another column city and pass it as href query string along with ID.
In the attached images you can see that ldInstID is blank
<!--
Name: dispParent.js
-->
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.2.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function($) {
//get the ID for the Issue from the Query String
// var issueID = getParameterByName("ID");
var ldInstID = getParameterByName("LeadInsitution");
//find the element with the "Add new item" link.
//note that if you have more than one list on your page, this just finds the first one
var anchorElement = $("a[title='Add a new item to this list or library.']");
//modify the "Add new item" link to call the "NewItem2" function and pass in the Issue ID.
//Be sure to put the path to your site below. You can use relative URL to the web application or the FQDN
// $(anchorElement).attr("href","javascript:NewItem2(event,'URL/Lists/Time/NewForm.aspx?IssueID=" + issueID + "');");
// $(anchorElement).attr("href","javascript:NewItem2(event,'URL/NewForm.aspx?IssueID=" + issueID + "&LdInst" + LdInst + "');");
$(anchorElement).attr("href","javascript:NewItem2(event,'URL/NewForm.aspx?LdInstID=" + ldInstID + "');");
//remove the "onclick" attribute from the anchor element as we aren't using it anymore
$(anchorElement).removeAttr("onclick");
});
// no, I didn't write this function from scratch, I found it at
// http://stackoverflow.com/questions/901115/get-query-string-values-in-javascript
// http://www.sharepointhillbilly.com/Lists/Posts/Post.aspx?ID=26
function getParameterByName(name)
{
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.href);
if(results == null)
return "";
else
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
</script>
variable passed-ID
Variable passed- ldInstID
Get parameter by id from URL:
function getURLParameter(parameterName) {
let result = null, temp = [];
location.search
.substr(1)
.split('&')
.forEach(function (item) {
temp = item.split('=');
if (temp[0] === parameterName)
result = decodeURIComponent(temp[1]);
});
return result;
}
if my url is http://example.com?id1=100&text=my%20text
console.log(getURLParameter('id1')); // 100
console.log(getURLParameter('text')); // "my text"

Add a variable in URL instead of replacing one

I'm facing a little issue with a javascript script. I'm trying to make my website multi languages. All is set in database, and my select works on pages where the URLs don't have variables. Here is my script:
<script type="text/javascript">
function submitForm() {
var thelang = document.getElementById('lang').options[document.getElementById('lang').selectedIndex].value;
window.location.href = window.location.pathname + '?lang=' + thelang;
}
</script>
In the homepage case, it works, and change http://localhost/ by http://localhost/?lang=en
But when I have an URL with a variable already set, it replaces it. From http://localhost/modules/product/product.php?id=1 I have http://localhost/modules/product/product.php?lang=en and the result I'd like is:
http://localhost/modules/product/product.php?id=1&lang=en
How to fix the script to make it works in both cases, or add the varibale, or glue it with an existing one?
Try checking to see if querystring params already exist in the URL.
function submitForm() {
var thelang = document.getElementById('lang').options[document.getElementById('lang').selectedIndex].value;
if (window.location.href.indexOf('?') >= 0) {
// There are already querystring params in the URL. Append my new param.
window.location.href = window.location.href + '&lang=' + thelang;
} else {
// There are not querystring params in the URL. Create my new param.
window.location.href = window.location.href + '?lang=' + thelang;
}
}
Update: Account for Subsequent Lang Changes
This assumes that the lang value will always be two characters.
function submitForm() {
var thelang = document.getElementById('lang').options[document.getElementById('lang').selectedIndex].value;
var newUrl = window.location.href;
var langIndex = newUrl.indexOf('lang=');
if (langIndex >= 0) {
// Lang is already in the querystring params. Remove it.
newUrl = newUrl.substr(0, langIndex) + newUrl.substring(langIndex + 8); // 8 is length of lang key/value pair + 1.
}
// Remove the final '?' or '&' character if there are no params remaining.
newUrl = newUrl.endsWith('?') || newUrl.endsWith('&') ? newUrl.substr(0, newUrl.length - 1) : newUrl;
newUrl = newUrl.indexOf('?') >= 0
? newUrl + '&lang=' + thelang // There are already querystring params in the URL. Append my new param.
: newUrl + '?lang=' + thelang; // There are not querystring params in the URL. Create my new param.
window.location.href = newUrl;
}
If I understand you correctly you want to add ?lang=en at the end. Unless there is already an id=1(or similar) there.
So you could just add an if statement, looking if there is .php writen at the end.
Not a very pretty solution but you are alreaady adding strings together so it doesn't matter
You can use the "search" element of window.location. See here for compatibility. You can then, concat the result with your desired parameter. BUT, you can do something way more complex (and secure) and check if there's already a parameter with that ID using a for + URLSearchParams.
const params = new URLSearchParams(window.location.search);
const paramsObj = Array.from(params.keys()).reduce(
(acc, val) => ({ ...acc, [val]: params.get(val) }), {}
);
This should fix it:
var currentUrl = window.location.origin + window.location.pathname;
var newUrl = currentUrl + (currentUrl.includes('?') ? ('&lang=' + thelang) : ('?lang=' + thelang));
window.location.href = newUrl;

Removing parameter values of a url in the next page using javascript only

I need to remove the values from the url after the ? in the next page the moment i click from my first page. I tried a lot of coding but could not get to a rite path. Need help.
The strings ex- Name, JobTitle and Date are dynamically generated values for ref.
Below are the links associated with the code:
Required url
file:///C:/Users/varun.singh/Desktop/www%20updated%2027.8.2015%20Old/www/Candidates/newOne.html?
Resultant url:
file:///C:/Users/varun.singh/Desktop/www%20updated%2027.8.2015%20Old/www/Candidates/newOne.html?Name=Name%201&JobTitle=Title%201&Date=Entered%20Date%201
listItem.onclick = function(){
var elementData=listData[this.id];
var stringParameter= "Name=" + elementData.name +"&JobTitle="+elementData.job_title+"&Date="+ elementData.entered_date;
//window.location.href = window.location.href.replace("ListCandidateNew", "newOne") + "?" + stringParameter;
window.location.href="file:///C:/Users/varun.singh/Desktop/www%20updated%2027.8.2015%20Old/www/Candidates/newOne.html?"
+ stringParameter;
}
This should work:
var url = file:///C:/Users/varun.singh/Desktop/www%20updated%2027.8.2015%20Old/www/Candidates/newOne.html?Name=Name%201&JobTitle=Title%201&Date=Entered%20Date%201
var index = url.lastIndexOf("?");
url = url.slice(0, index+1); // index+1 so that "?" is included
Thanks everond for trying and attempting to answer my problem. Well, i have found the solution using window.sessionStorage as i wanted by keeping the string parameter alive to pass the values. Here is the full code:
I have two pages for passing the value from one to another: ListCandidateNew.html and newOne.html
ListCandidateNew.html
listItem.onclick = function()
{
var elementData=listData[this.id];
var stringParameter= "Name=" + elementData.name +"&JobTitle="+elementData.job_title+"&Date="+ elementData.entered_date;
window.sessionStorage['Name'] = elementData.name;
window.sessionStorage['JobTitle'] = elementData.job_title;
window.sessionStorage['Date'] = elementData.entered_date;
**newOne.html**
function LoadCandidateDetail()
{
document.getElementById('Name').innerHTML = window.sessionStorage['Name'];
document.getElementById('JobTitle').innerHTML = window.sessionStorage["JobTitle"];
document.getElementById('Date').innerHTML = window.sessionStorage["Date"];
}

Get String value between two strings through javascript

I want to get the string value between ";L0|" and ";GTSet" from the following type of strings.
var test = "GP0|#9d72d96c-407f-4e45-b2e6-9361faf5808a;L0|#09d72d96c-407f-4e45-b2e6-9361faf5808a|Travel;GTSet|#ac96f075-b7d2-4e90-8dc2-da8875f395fc";
var test2 = "GP0|#15a06b93-f7aa-4dda-b0d6-7bf2d2905f27;L0|#015a06b93-f7aa-4dda-b0d6-7bf2d2905f27|Special Event;GTSet|#ac96f075-b7d2-4e90-8dc2-da8875f395fc";
Here is what i have done already.
var str = test2.match(";L0|" + "(.*?)" + ";GTSet");
alert(str[1]);
and this returns a string from the very beginning till the ";GTSet"
Jsfiddle link here
I guess you are getting this value from SharePoint Search results, right? If so, according to Automatically created managed properties in SharePoint Server 2013:
Data format for Managed Metadata.
To query for items tagged with a Managed Metadata field, you have to
use the Unique Identifier for each label. You can find the Unique
Identifier for each term in a term set in the Term Store Management
Tool, on the GENERAL tab. In addition, the data format that is used in
the query has to specify from which level in the term set the query
should apply. This specification is set by adding one of the following
prefixes to the Unique Identifier:
To query for all items that are tagged with a term: GP0|#
To query for all items that are tagged with a child of term: GPP|#
To query for all items that are tagged with a term from a term set: GTSet|#
Based on this information the following example demonstrates how to parse search result value for managed metadata:
function parseTaxonomySearchResultValue(val){
var taxValue = {TermSetGuids: [], TermValues: []};
var parts = val.split(';');
parts.forEach(function(part){
if (part.startsWith("GP0|#")) //term?
{
var termGuid = part.replace("GP0|#", "");
taxValue.TermValues.push({ TermGuid: termGuid});
}
else if (part.startsWith("GTSet|#")) //term set?
{
taxValue.TermSetGuids.push(part.replace("GTSet|#", ""));
}
else if (part.startsWith("L0|#")) //Term with label?
{
var termParts = part.replace("L0|#0", "").split('|');
var termGuid = termParts[0];
var termLabel = termParts[1];
var result = taxValue.TermValues.filter(function(tv){
return tv.TermGuid == termGuid;
});
if (result.length == 0)
taxValue.TermValues.push({TermGuid : termGuid, Label : termLabel});
else
result[0].Label = termLabel;
}
});
return taxValue;
}
//Usage
var taxValue = 'GP0|#9d72d96c-407f-4e45-b2e6-9361faf5808a;L0|#09d72d96c-407f-4e45-b2e6-9361faf5808a|Travel;GTSet|#ac96f075-b7d2-4e90-8dc2-da8875f395fc';
var taxValue = parseTaxonomySearchResultValue(taxValue);
document.getElementById('output').innerHTML = "Term info:<br/>" + "Guid= " + taxValue.TermValues[0].TermGuid + "<br/> Label= " + taxValue.TermValues[0].Label;
<div id='output'/>

Change url query string value using jQuery [duplicate]

This question already has answers here:
Updating existing URL querystring values with jQuery
(12 answers)
Closed 9 years ago.
I have an example URL like:
http://domain.com/Documents/?page=1&name=Dave&date=2011-01-01
The query string contains the current page number and two additional filters (name and date).
Using the following URL parser: https://github.com/allmarkedup/purl I am able to access certain parts of the URL such as just the page number.
I'm trying to create a way for a user to be able to type a number into a textbox and then load that page number whilst keeping all the other query strings intact.
$(document).ready(function () {
$('.pageNum').live('keyup', function (e) {
e.preventDefault();
if (e.which == 13) {
var currentUrl = window.location.href;
var parsedUrl = $.url(currentUrl);
var currentPageNum = parsedUrl.param('page');
var newPageNum = $(this).val();
var newUrl = //
window.location.href = newUrl;
}
});
});
So when a user hits return on the pageNum textbox, it will get the current page url, parse it, then find out the current page number and then I need a way to replace the value of the page number with the new value in the textbox to create a new url, and then finally refresh the page using this new url.
Is it possible to change the param value and then add it back in?
Note: The additional parameters could be anything, so I can't manually add them onto the pathname with the new page number!
If you only need to modify the page num you can replace it:
var newUrl = location.href.replace("page="+currentPageNum, "page="+newPageNum);
purls $.params() used without a parameter will give you a key-value object of the parameters.
jQuerys $.param() will build a querystring from the supplied object/array.
var params = parsedUrl.param();
delete params["page"];
var newUrl = "?page=" + $(this).val() + "&" + $.param(params);
Update
I've no idea why I used delete here...
var params = parsedUrl.param();
params["page"] = $(this).val();
var newUrl = "?" + $.param(params);

Categories