Here's the situation:
function STP() { var LOC = window.location.href;
var CSV = LOC.substring(LOC.indexOf(',')+1);
var ARR = CSV.split(',');
var STR = ARR[ARR.length -1 ];
var POS = window.document.getElementById(STR).offsetTop;
alert( STR ); };
Explained:
When the page loads, the onload calls the script.
The script gets the location.href and Extracts the element ID by
creating an array and referencing the last one.
So far so good.
I then use that to reference an element ID to get its position.
But it doesn't work.
The STR alert indicates the proper value when it's placed above POS, not below. The script doesn't work at all below that point when the STR var reference is used.
However if I do a direct reference to the ID ('A01') no problem.
Why does one work and not the other when both values are identical? I've tried other ways like using a hash instead of a comma and can extract the value that with .location.hash, but it doesn't work either.
The problem is that when you do
LOC.substring(LOC.indexOf(',') + 1);
you're putting everything after the , into the CSV variable. But there is a space between the comma and the 'A01'. So, the interpreter reduces it to:
var POS = window.document.getElementById(' A01').offsetTop;
But your ID is 'A01', not ' A01', so the selector fails.
function STP() {
var LOC = 'file:///M:/Transfers/Main%20Desktop/Export/USI/2018/Catalog/CAT-Compilations-01a.htm?1525149288810, A01';
var CSV = LOC.substring(LOC.indexOf(',') + 1);
var ARR = CSV.split(',');
var STR = ARR[ARR.length - 1];
console.log(`'${STR}'`);
}
STP();
To solve this, you can increase the index by one:
LOC.substring(LOC.indexOf(',') + 2);
But it would probably be better not to put spaces in URLs when not necessary - if possible, send the user to 'file:///M:/Transfers/Main%20Desktop/Export/USI/2018/Catalog/CAT-Compilations-01a.htm?1525149288810,A01' instead.
Related
I have an online store that has limited access to make any correct edits to code.
I am trying to implement proper Price Schema as they have:
<span itemprop="price">$57.00</span>
This is incorrect.
It needs to be set up like this
<span itemprop="priceCurrency" content="USD">$</span>
<span itemprop="price">57.00</span>
Is there something in JavaScript or jQuery that can manipulate this by separating the Currency Symbol and Price?
Thanks
You get the ELEMENT text:
var value = $("span[itemprop='price'").text();
Then you could generate the html using regex like:
var html = '$57.00'.replace(/([^\d])(\d+)/,
function(all, group1, group2){
return 'some html here =' + group1 + '= more hear =' + group2 });
Might not be 100% bug-free, but it should get you started:
<script type="text/javascript">
var n = document.getElementsByTagName('*')
for(var i=0;i<n.length;i++)
{
if(n[i].hasAttribute('itemprop')) //get elements with itemprop attribute
{
var p = n[i].parentNode
var ih = n[i].innerHTML //grab the innerHTML
var num = parseFloat(ih) //get numeric part of the innerHTML - effectively strips out the $-sign
n[i].innerHTML = num
//create new span & insert it before the old one
var new_span = document.createElement('span')
new_span.innerHTML = '$'
new_span.setAttribute('itemprop', 'priceCurrency')
new_span.setAttribute('currency', 'USD')
p.insertBefore(new_span, n[i])
}
}
</script>
Somthing along the lines of
// find all span's with itemprop price
document.querySelectorAll("span[itemprop='price']").forEach(function(sp){
// grab currency (first char)
var currency = sp.innerText.substr(0,1);
// remove first char from price val
sp.innerText = sp.innerText.substr(1);
// create new element (our price-currency span)
var currencySpan = document.createElement("span");
currencySpan.innerText = currency;
currencySpan.setAttribute("itemprop", "priceCurrency");
currencySpan.setAttribute("content", "USD");
// Append it before the old price span
sp.parentNode.insertBefore(currencySpan, sp);
});
Should do what your after.
See demo at: https://jsfiddle.net/dfufq40p/1/ (updated to make effect more obvious)
This should work -- querySelectorAll should be a bit faster, and the regex will work with more than just USD, I believe.
function fixItemPropSpan() {
var n = document.querySelectorAll('[itemprop]');
for (var i = 0; i < n.length; i++) {
var p = n[i].parentNode;
var ih = n[i].innerHTML;
var num = Number(ih.replace(/[^0-9\.]+/g, ""));
n[i].innerHTML = num;
//create new span & insert it before the old one
var new_span = document.createElement('span');
new_span.innerHTML = '$';
new_span.setAttribute('itemprop', 'priceCurrency');
new_span.setAttribute('currency', 'USD');
p.insertBefore(new_span, n[i]);
}
}
Here is a suggestion of how you can make this work, though i would not suggest doing it like this (too many cases for content="").
Example of the logic you could use to transform the incorrect format to the correct one.
Hope you find it useful. :]
var url = window.location.href.toString();
the above line gives me the url of my current page correctly and my url is:
http://localhost/xyzCart/products.php?cat_id=35
However, using javascript how can i get only a portion of the url i.e. from the above url i just want
products.php?cat_id=35
How to accomplish this plz help.I have looked at similar questions in this forum but none were any help for me..
You can sliply use this:
var url = window.location.href.toString();
var newString = url.substr(url.lastIndexOf(".") + 1));
This will result in: php?cat_id=35
Good luck /Zorken17
You can use the location of the final /:
var page = url.substr(url.substr(0, (url + "?").indexOf("?")).lastIndexOf("/") + 1);
(This allows for / in a query string)
You can get your desired result by using javascript split() method.check this link for further detail
https://jsfiddle.net/x06ywtvo/
var urls = [
"http://localhost/xyzCart/products.php?cat_id=35",
"http://localhost/xyzCart/products.php",
"http://www.google.com/xyzCart/products.php?cat_id=37"
];
var target = $('#target');
for(var i=0;i<urls.length;i++){
var index = urls[i].indexOf("xyzCart");
var sub = urls[i].substring(index, urls[i].length);
target.append("<div>" + sub + "</div>");
}
Try the folowing javacript code to get the part you need. It splits up your url by the "/"s and takes the fourth part. This is superior to substr solutions in terms of descriptive clarity.
url.split("/")[4]
Or if url can contain more "/" path parts, then simply take the last split part.
var parts = url.split("/");
console.log( parts[parts.length-1] );
You will get all necessary values in window.location object.
Kindly check on following CodePen Link for proper output.
I have added parameter test=1
Link: http://codepen.io/rajesh_dixit/pen/EVebJe?test=1
Code
(function() {
var url = window.location.pathname.split('/');
var index = 1;
document.write("URL: ");
document.write(window.location.href);
document.write("<br/> Full Path: ");
document.write(window.location.pathname);
document.write("<br/> Last Value:")
// For cases where '/' comes at the end
if(!url[url.length - index])
index++;
document.write(url[url.length-index])
document.write("<br/> Query Parameter: ");
document.write(window.location.search.substring(1));
})()
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"];
}
I've node app and Im getting in some header the following URL and I need to parse it and change the content of 3000 to 4000 ,How can I do that since Im getting "two" URLs in the req.headers.location
"http://to-d6faorp:51001/oauth/auth?response_type=code&redirect_uri=http%3AF%2Fmo-d6fa3.ao.tzp.corp%3A3000%2Flogin%2Fcallback&client_id=x2.node"
The issue is that I cannot use just replace since the value can changed (dynmaic value ,now its 3000 later can be any value...)
If the part of the URL you always need to change is going to be a parameter of redirect_uri then you just need to find the index of the second %3A that comes after it.
Javascript indexOf has a second parameter which is the 'start position', so you can first do an indexOf the 'redirect_uri=' string, and then pass that position in to your next call to indexOf to look for the first '%3A' and then pass that result into your next call for the %3A that comes just before your '3000'. Once you have the positions of the tokens you are looking for you should be able to build a new string by using substrings... first substring will be up to the end of your second %3A and the second substring will be from the index of the %2F that comes after it.
Basically, you will be building your string by cutting up the string like so:
"http://to-d6faorp:51001/oauth/auth?response_type=code&redirect_uri=http%3AF%2Fmo-d6fa3.ao.tzp.corp%3A"
"%2Flogin%2Fcallback&client_id=x2.node"
... and appending in whatever port number you are trying to put in.
Hope this helps.
This code should get you what you want:
var strURL = "http://to-d6faorp:51001/oauth/auth?response_type=code&redirect_uri=http%3AF%2Fmo-d6fa3.ao.tzp.corp%3A3000%2Flogin%2Fcallback&client_id=x2.node";
var strNewURL = strURL.substring(0,strURL.indexOf("%3A", strURL.indexOf("%3A", strURL.indexOf("redirect_uri") + 1) + 1) + 3) + "4000" + strURL.substring(strURL.indexOf("%2F",strURL.indexOf("%3A", strURL.indexOf("%3A", strURL.indexOf("redirect_uri") + 1) + 1) + 3));
Split the return string in its parameters:
var parts = req.headers.location.split("&");
then split the parts into fieldname and variable:
var subparts = [];
for (var i = 1; i < parts.length; i++)
subparts[i] = parts[i].split("=");
then check which fieldname equals redirect_uri:
var ret = -1;
for (var i = 0; i < subparts.length; i++)
if (subpart[i][0] == "redirect_uri")
ret = i;
if (ret == -1)
// didnt find redirect_uri, somehow handle this error
now you know which subpart contains the redirect_uri.
Because I dont know which rules your redirect_uri follows I can't tell you how to get the value, thats your task but the problem is isolated to subparts[ret][1]. Thats the string which contains redirect_uri.
For a client's requirement, I have set out several images as follows:
img/img1.jpg
img/img2.jpg
img/img3.jpg
...
img/img4.jpg.
Now, I need to make the function that loads images dynamic. At the moment, the current solution is as follows:
// Grab the last image path
var lastImagePath = $("lastImage").attr("src");
// Increment the value.
var nextImagePath = "img/img" + (+lastImagePath.replace("img/img").replace(".jpg") + 1) + ".jpg";
// So on.
I was wondering if there's a cleaner way to increment the number?
Slightly cleaner:
var nextImagePath = lastImagePath.replace(/\d+/, function (n) { return ++n; });
This uses the version of replace that accepts a regular expression and a function.