Get last string from URL with jQuery - javascript

Im trying to get the last string from a URL for example...
http://www.mywebsite/blog/this-post
I want to use jQuery to get 'this-post'
Ive the following...
$('img.gigthumb').each(function(){
var foo = $(this).parent().attr('href').split('/');
$(this).attr('src','/lic/wp-content/uploads/2012/01/'+foo[1]+'.jpg');
})
only it doesn't work and I presume thats because I have multiple '/' within the URL, any idea how to target just the last?
Hope this makes sense!

This is precisely what .pop() is made for:
$('img.gigthumb').each(function(){
var foo = $(this).parent().attr('href').split('/').pop();
$(this).attr('src','/lic/wp-content/uploads/2012/01/' + foo + '.jpg');
});

Don't use the element with index 1 of foo, but the last one:
$(this).attr('src','/lic/wp-content/uploads/2012/01/'+foo[foo.length-1]+'.jpg');

Splitting with "/" will give you the array:
foo[0] = "http:"
foo[1] = ""
foo[2] = "www.mywebsite"
foo[3] = "blog"
foo[4] = "this-post"
If you want to get the last item regardless of the size of the array do:
foo[foo.length - 1]
or as Joseph mentioned: foo.pop()

Following your example you need the last part of the splits:
$('img.gigthumb').each(function(){
var foo = $(this).parent().attr('href').split('/');
var last = foo.length - 1;
$(this).attr('src','/lic/wp-content/uploads/2012/01/'+foo[last]+'.jpg');
})

var foo = $(this).parent().attr('href').replace(/^.*\\/, '');

Related

Javascript ID Extracted From String Not Working

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.

How to get a specific portion of the url using javascript?

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));
})()

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"];
}

How to fix Javascript NaN issue?

Here is my code
var total_center_buttons=$('.center_button').length;
var center_button_height=$('.center_button:first-child').height();
var total_center_button_height=total_center_buttons + center_button_height;
alert(total_center_button_height);
Here total_center_button value =3
and center_button_height is 40 while alerting them separately.It returns NaN. I tried ParseInt also but result is same.Please suggest me the solution.Thanks in advance.
Krishna
We have to guess, since you haven't quoted the DOM, but my guess is that $('.center_button:first-child') doesn't match any elements. Calling height() on an empty set returns undefined. When you try to add it to the number from the previous line, you get NaN.
I suspect you didn't want :first-child, but rather
var center_button_height=$('.center_button').first().height();
...but again without seeing the DOM, it's hard to say. To avoid repeated DOM lookups, you'd do this:
var buttons = $('.center_button');
var total_center_buttons = buttons.length;
var center_button_height = buttons.first().height();
var total_center_button_height = total_center_buttons + center_button_height;
alert(total_center_button_height);
.center_button:first-child will only match an element that both has the class center_button and is the first child of its parent element. My suggestion above is based on the assumption that you really wanted the first of the buttons, and that the buttons aren't the first thing in their parent.
Finally: That + in
var total_center_button_height = total_center_buttons + center_button_height;
looks suspicious. Again without seeing the markup it's hard to say, but you may have meant * there.
Mate,
there's a typo in your post. Notice the code line where you assign the value to total_center_button_height
var total_center_button_height = center_button_height + total_center_button_height;
That's where the problem is, the variable to the right of the addition operation (total_center_button_height) does not exist yet. Replace that line with...
var total_center_button_height = center_button_height + total_center_buttons;
Pretty straight forward
Hope it helps
Leo
may be you need to write this
var total_center_button_height=center_button_height + total_center_buttons;
alert(total_center_button_height);
you can check for "isNaN" function, this is to check whether the parameter is number or not.
Try this:
$(function(){
var total_center_buttons = $('.center_button').length > 0 ? $('.center_button').length : 0;
if(total_center_buttons !=0){
var center_button_height=$('.center_button:first-child').height();
var total_center_button_height = center_button_height + total_center_button_height;
alert(total_center_button_height);
}
});
you are doing this:
var total_center_button_height=center_button_height + total_center_button_height;
i.e. total_center_button_height is used in the same line where it is declared. At this time it is undefined.
i guess, you should be doing:
var total_center_button_height=center_button_height + total_center_buttons;
Try something like this:
var total_center_buttons=$('.center_button').length;
if (typeof total_center_buttons != 'undefined') {
var center_button_height=$('.center_button:first-child').height();
var total_center_button_height=total_center_buttons + center_button_height;
alert(total_center_button_height);
}

Jquery convert object to string and slice

Via ajax-based script i get object:
for example:
item.TYP_PCON_START
which value is, for example 201212...
When i try to slice him, i get oject error...
How could i slice this object so, that for example i get 2012, or better set two last numbers on furst place and add dot, like:
12.2012
How could i do this? (i append this text as value of select list)
You need to slice the string property, not the object itself:
item.TYP_PCON_START.slice(-2) + '.' + item.TYP_PCON_START.slice(0, 4);
> '12.2012'
http://jsfiddle.net/4Hdme/
edit: In the case that your property is a number, you must convert it to a string before attempting to slice it:
var propertyAsString = item.TYP_PCON_START.toString();
propertyAsString.slice(-2) + '.' + propertyAsString.slice(0, 4);
> '12.2012'
http://jsfiddle.net/4Hdme/1/
var a = item.TYP_PCON_START,
a = a+"",
a = a.split("");
a.splice(2,0,".");
a = a.join("");
a = parseFloat(a);
console.log(a);

Categories