On my website:
http://mywebsite.com/1.html
I want to use the
window.location.pathname
to get the last part of the url:
1.html
and since I have all my webpages in numbers I want to add 1 to the current url so that when I click a button it will redirect me to the next page:
var url = 'http://mywebsite.com/' + window.location.pathname;
function nextImage (){
url = url + 1;
}
any ideas why this is not working ?
Your example wasn't working because you are trying to add 1 to a string that looks like this: "1.html". That will just get you this "1.html1" which is not what you want. You have to isolate the numeric part of the string and then convert it to an actual number before you can do math on it. After getting it to an actual number, you can then increase its value and then combine it back with the rest of the string.
You can use a custom replace function like this to isolate the various pieces of the original URL and replace the number with an incremented number:
function nextImage() {
return(window.location.href.replace(/(\d+)(\.html)$/, function(str, p1, p2) {
return((Number(p1) + 1) + p2);
}));
}
You can then call it like this:
window.location.href = nextImage();
Demo here: http://jsfiddle.net/jfriend00/3VPEq/
This will work for any URL that ends in some series of digits followed by .html and if you needed a slightly different URL form, you could just tweak the regular expression.
This is more robust:
mi = location.href.split(/(\d+)/);
no = mi.length - 2;
os = mi[no];
mi[no]++;
if ((mi[no] + '').length < os.length) mi[no] = os.match(/0+/) + mi[no];
location.href = mi.join('');
When the URL has multiple numbers, it will change the last one:
http://mywebsite.com/8815/1.html
It supports numbers with leading zeros:
http://mywebsite.com/0001.html
Example
Even it is not a good way of doing what you want try this hint:
var url = MUST BE A NUMER FIRST
function nextImage (){
url = url + 1;
location.href='http://mywebsite.com/' + url+'.html';
}
What you're doing is appending a "1" (the string) to your URL. If you want page 1.html link to page 2.html you need to take the 1 out of the string, add one to it, then reassemble the string.
Why not do something like this:
var url = 'http://mywebsite.com/1.html';
var pageNum = parseInt( url.split("/").pop(),10 );
var nextPage = 'http://mywebsite.com/'+(pageNum+1)+'.html';
nextPage will contain the url http://mywebsite.com/2.html in this case. Should be easy to put in a function if needed.
Related
I have a series of pages where I need to get a specific code for a button.
I want to put the code which is in the url into a variable with jQuery.
An example URL is www.example.com/folder/code/12345/
I want to get the number part in a variable called (siteCode)
Thanks in advance for any answers.
jquery / Pseudo code:
var siteCode;
// start function
function imageCode(){
siteCode // equals number part of URL
$('.button').attr('src', 'http:www.example.com/images/'+siteCode+'.jpg');
}
You can use the following code to get the last part of the url.:
var value = url.substring(url.lastIndexOf('/') + 1);
I'd suggest:
var URI = 'www.example.com/folder/code/12345/',
parts = URI.split('/'),
lastPart = parts.pop() == '' ? parts[parts.length - 1] : parts.pop();
JS Fiddle demo.
var str="url";
str.split("/")[3]
you can use split
There is one best way to take last part of URL is like following which generally has been used in real implementation.
There are Some loopholes in previously given answer was:
1.Consider what if there is a url like www.example.com/folder/code/12345 (Without '/' forward slash) Than none of the above code will work as per expectation.
2.Consider if folder hierarchy increases like www.example.com/folder/sub-folder/sub-sub-folder/code/12345
$(function () {
siteCode = getLastPartOfUrl('www.example.com/folder/code/12345/');
});
var getLastPartOfUrl =function($url) {
var url = $url;
var urlsplit = url.split("/");
var lastpart = urlsplit[urlsplit.length-1];
if(lastpart==='')
{
lastpart = urlsplit[urlsplit.length-2];
}
return lastpart;
}
Also try using regex
var url = "www.example.com/folder/code/12345";
var checkExt = /\d$/i.test(url);
if (checkExt) {
alert("Yup its a numeric");
} else {
alert("Nope");
}
I have a bunch of images in a folder which are all named as numbers. The first one is displayed on document load.
<img src="image/01.jpg" />
I want to use jQuery to flick through the images. In other words, I want to convert the HTML to a string and then increase the value of what is currently "01".
So far I have:
$(document).ready(function(){
$("button").click(function(){
var $n = $("img").html(htmlString(17));
$n.val(Number($n.val())+1);
});
});
The bit that I'm sure I'm completely wrong on is the selecting of the digit (i.e delcaring var $n. I've tried to convert the HTML to a string there and count along the characters but I'm not even sure if that's the right route to be taking; I can't find anything similar anywhere.
Thanks.
img element doesn't have html content, apart from that you are using html as setter not getter. You can replace the src attribute's value using replace method:
$('img').prop('src', function(_, src) {
return src.replace(/\d+/, function(n) {
var num = +n + 1;
return num.toString().length === 1 ? '0' + num.toString() : num;
});
});
http://jsfiddle.net/Bb84Q/
You can just
1)catch the src value in a js variable
2) using substr function get rid of the "image/" part.
3) Then using split() on "." take the first array slot's value.
4)Convert that to integer using intVal() and
5) then increment the value
var source = "image/01.jpg";
var number = source.split(".")[0].split("/")[1];
number = (number *1) + 1
var newsource = "image/" + number + ".jpg";
this is how you'd actually get source
var source = $("img").attr('src');
just realized that this will make "image/2.jpg" , you could use a data-number attribute, you could re-name the images that are 1 - 9 , but this gives you an idea
Here is an example of url structure I'll be working with (ignore the age of electric video :) )
http://www.youtube.com/embed/ABCumLrphFA?&start=20&end=50
Basically I want to be able to grab the video id, the chosen start time (20) and end chosen time (50) and save them as variables from any URL that follows the pattern above.
So a simple setup is this:
var url = 'http://www.youtube.com/embed/ABCumLrphFA?&start=20&end=50'
// get youtube id
function youtubeid(url) {
var ytid = url.match(dont know);
ytid = ytid[1];
return ytid;
}
// get youtube start time
function youtubeStart(url) {
var ytStart = url.match(dont know);
ytStart=ytStart[1];
return ytStart;
}
// get youtube end time
function youtubeEnd(url) {
var ytEnd = url.match(dont know);
ytEnd=ytEnd[1];
return ytEnd;
}
If you could help me fill in the blanks that would be most amazing. I've been staring at regex documentation for a while now and just getting more and more confused.
This other Stack Overflow answer may help you. I used Peter Mortensen's answer below.
Get query string values in JavaScript
To obtain the actual YouTube Id, you can use this regular expression:
http:\/\/www.youtube.com\/embed\/(.{11})
That regex will return the value in parenthesis. You can test it here:
http://www.pagecolumn.com/tool/regtest.htm
Sample code:
var url = 'http://www.youtube.com/embed/ABCumLrphFA?&start=20&end=50'
// get youtube id
function youtubeid(url) {
var ytid = url.match(/http:\/\/www.youtube.com\/embed\/(.{11})/);
ytid = ytid[1];
return ytid;
}
alert(youtubeid(url));
function getParameterByName(name, url) {
var match = RegExp('[?&]' + name + '=([^&]*)')
.exec(url);
return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}
alert(getParameterByName('start', url));
alert(getParameterByName('end', url));
1
/http:\/\/www\.youtube\.com\/embed\/([^?]+)/
2
/http:\/\/www\.youtube\.com\/embed\/[^?]+.*[?&]start=(\d+)(?:&|$)/
3
/http:\/\/www\.youtube\.com\/embed\/[^?]+.*[?&]end=(\d+)(?:&|$)/
This'll only work if you know your URLs will look exactly like the one you gave (no extra query parameters; start and end always in that order; no HTTPS; etc.). But you can get them all at once:
js> str = 'http://www.youtube.com/embed/ABCumLrphFA?&start=20&end=50'
http://www.youtube.com/embed/ABCumLrphFA?&start=20&end=50
js> rxp = /http:\/\/www.youtube.com\/embed\/(.*)\?&start=(\d+)?&end=(\d+)?/
/http:\/\/www.youtube.com\/embed\/(.*)\?&start=(\d+)?&end=(\d+)?/
js> result = rxp.exec(str)
http://www.youtube.com/embed/ABCumLrphFA?&start=20&end=50,ABCumLrphFA,20,50
js> result[0]
http://www.youtube.com/embed/ABCumLrphFA?&start=20&end=50
js> result[1]
ABCumLrphFA
js> result[2]
20
js> result[3]
50
I believe it's possible to write a regex that can cope with all the quirks I mentioned above, but it's way uglier and makes it harder to understand. Anyway - hope this helps!
See also: JavaScript Regex Escape Sequences and JavaScript Regex Methods
var url = "http://www.youtube.com/embed/ABCumLrphFA?&start=20&end=50";
// get youtube id
function youtubeid(url) {
q = url.substring(url.lastIndexOf("/")+1);
var ytid = q.substring(q.lastIndexOf("?"), -1);
return ytid;
}
// get youtube start time
function youtubeStart(url) {
q = url.substring(url.lastIndexOf("/")+1);
var ytStart = q.substring(q.indexOf("&start")+7,q.indexOf("&end"));
return ytStart;
}
// get youtube end time
function youtubeEnd(url) {
q = url.substring(url.lastIndexOf("/")+1);
var ytEnd = q.substring(q.indexOf("&end")+5);
return ytEnd;
}
console.log(youtubeid(url));
console.log(youtubeStart(url));
console.log(youtubeEnd(url));
To retrieve the id
url.match(/embed\/(.*)\?/)
The best way to retrieve URL params (start and end) is to do something like Get Querystring with Dojo Then you could use the following to retrieve start and end
var qs = getUrlParams();
console.log("start is " + qs.start + " and end is " + qs.end )
I have script which allows to display Bing search results. I can call for the search results url's like this:
'<p class="width">',imgResult.DisplayUrl,'</p>' ,
The problem is that sometimes the url is to long an 'sloppy' like this:
http://www.art-wallpaper.net/Game-Wallpapers/Assassins-Creed-Brotherhood/imagepages/image3.htm
I would like to 'hide' or 'delete' the beginning of the url (http://www.) and do the same from /Game... etc This way I can get a 'clean' and 'short' url like: art-wallpaper.net I there a (simple) way of doing this?
Perhaps a JavaScript function like this.
function shorten(str)
{
// Get rid of the protocol
str = str.replace("http://", "");
str = str.replace("https://", "");
// Return the domain-part of the URL
return str.split("/")[0];
}
Pass your URL to the JavaScript function prior to printing it.
Untested.
url="http://www.art-wallpaper.net/Game-Wallpapers/Assassins-Creed-Brotherhood/imagepages/image3.htm";
pathArray =url .split( '/' );
host = pathArray[2];
alert(host);// alert "www.art-wallpaper.net"
and,
pathArray = "http://www.art-wallpaper.net/Game-Wallpapers/Assassins-Creed-Brotherhood/imagepages/image3.htm".split( '/' );
host = pathArray[2].substring(4);
alert(host);// alert "art-wallpaper.net"
The problem statement is like this: I have a contract. On renewal on every month the contract name should append with renewal identifier. For example at beginning the name is myContract then on first renewal name should be myContract-R1, next renewal name should be myContract-R2 and so on.. On each renewal, the name should automatically change. So in Jquery how can I do this?
This is a JavaScript question, not a jQuery question. jQuery adds little to JavaScript's built-in string manipulation.
It sounds like you want to take a string in the form "myContract" or "myContract-Rx" and have a function that appends "-R1" (if there's no "-Rx" already) or increments the number that's there.
There's no shortcut for that, you have to do it. Here's a sketch that works, I expect it could be optimized:
function incrementContract(name) {
var match = /^(.*)-R([0-9]+)$/.exec(name);
if (match) {
// Increment previous revision number
name = match[1] + "-R" + (parseInt(match[2], 10) + 1);
}
else {
// No previous revision number
name += "-R1";
}
return name;
}
Live copy
You can use a regular expression for this:
s = s.replace(/(-R\d+)?$/, function(m) {
return '-R' + (m.length === 0 ? 1 : parseInt(m.substr(2), 10) + 1);
});
The pattern (-R\d+)?$ will match the revision number (-R\d+) if there is one (?), and the end of the string ($).
The replacement will return -R1 if there was no revision number before, otherwise it will parse the revision number and increment it.
how you get renewal number? Calculating from date, or getting from database?
var renewal = 1,
name = 'myContract',
newname = name+'R'+renewal;
or maybe like
$(function(){
function renew(contract){
var num_re = /\d+/,
num = contract.match(num_re);
if (num==null) {
return contract+'-R1';
} else {
return contract.replace(num_re,++num[0]);
}
}
var str = 'myContract';
new_contract = renew(str); // myContract-1
new_contract = renew(new_contract); // myContract-2
new_contract = renew(new_contract); // myContract-3
});
Here jQuery can't help you. It's pure JavaScript working with strings
P.S. I have here simple reg exp, that's not concrete for your example (but it works). Better use reg-exp from example of T.J. Crowder