Javascript - get current page URL without pagination numbers
Say I have a URL for an article:
http://domain.com/blog/articles/title-here/
And it has about 5 pages, so as you go through each page, you get:
http://domain.com/blog/articles/title-here/ OR http://domain.com/blog/articles/title-here/1
http://domain.com/blog/articles/title-here/2
http://domain.com/blog/articles/title-here/3
http://domain.com/bl开发者_JAVA技巧og/articles/title-here/4
http://domain.com/blog/articles/title-here/5
I know that the following code will get the full current URL (aka including the page #):
var u = window.location.href;
But is there a way to limit it so that the page # is NOT a part of the variable "u"?
Perhaps there's a regex or something I should add in there..? (I'm fairly new to javascript, so not sure how to apply this?)
var u = window.location.href.match(/.*[/][^\d]*/)[0]
Would that work for you?
Edit
I changed it... again :P
NOTE: Regex is a more complicated version of Joseph's and still suffers from the same bug. Will undelete when I fix it.
Joseph's answer is good, but it has a minor bug: it will drop the last part of the URL if you have an URL like:
http://domain.com/blog/articles/title-here
You can use this instead:
var u = window.location.href.match(/(.*)(\/\d*)/)[1]
How the regex works:
/ # delimiter
(.*?) # match anything and put in capture group 1
(\/ # match the forward slash
\d*) # match zero or more digits
/ # delimiter
var l = window.location;
l.href.replace(l.pathname, l.pathname.split(/\/[0-9]+$/)[0]);
try it in the console at this URL
Regex would do it. But in this case, you could just turn it into an array, strip of the end item, and re-serialize it.
var a = 'http://domain.com/blog/articles/title-here/2'.split('/');
a.splice(-1, 1);
a.join('/');
精彩评论