Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get page url using javascript

Tags:

javascript

Could someone recommend a way to get page name from a url using JavaScript?

For instance if I have:

http://www.cnn.com/news/1234/news.html?a=1&b=2&c=3

I just need to get "news.html" string

Thanks!

like image 820
Alex Avatar asked Mar 11 '10 16:03

Alex


People also ask

How do I get the URL of a webpage?

Answer: Use the window. location. href Propertyhref property to get the entire URL of the current page which includes host name, query string, fragment identifier, etc. The following example will display the current url of the page on click of the button.

How do I get the current page number in JavaScript?

var lighboxHeight = (pagenumber-1)*window.

Which method returns the URL of the current page?

The window.location.href property returns the URL of the current page.


2 Answers

You can do this pretty easily via window.location.pathname parsing:

var file, n;

file = window.location.pathname;
n = file.lastIndexOf('/');
if (n >= 0) {
    file = file.substring(n + 1);
}
alert(file);

...or as others have said, you can do it with a regexp in one line. One kinda dense-looking line, but with a comment above it, should be a good way to go.

like image 182
T.J. Crowder Avatar answered Oct 25 '22 12:10

T.J. Crowder


I think it's

window.location.pathname.replace(/^.*\/([^/]*)/, "$1");

So,

var pageTitle = window.location.pathname.replace(/^.*\/([^/]*)/, "$1");
like image 44
Pointy Avatar answered Oct 25 '22 11:10

Pointy