8

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!

0

4 Answers 4

15

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.

Sign up to request clarification or add additional context in comments.

1 Comment

+1 I'm impressed with the power of regex, but I can't read 'em.
5

I think it's

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

So,

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

5 Comments

I think you need to escape forward slashes there. :)
Nice! I never knew about pathname!
Don't you want a $ at the end of that? To avoid partial matches?
Answering myself: Not in my experiments, no.
I figured the * would eat up the rest of the pathname string, which I think is what the OP wanted.
3
var url = "http://www.cnn.com/news/1234/news.html?a=1&b=2&c=3";
url = url.replace(/^.*\//, "").replace(/\?.*$/, "");

You can substitute url with window.location

1 Comment

As a note, doing window.location.replace(/^.*\//, "").replace(/\?.*$/, ""); will redirect you.
0

You might want to also find file paths on a local disk, and you might not want to include any hash or get strings in the path-

String.prototype.fileName= function(){
 var f, s= this.split(/[#\?]/, 1)[0].replace(/\\/g,'/');
 s= s.substring(s.lastIndexOf('/')+ 1);
 f=  /^(([^\.]+)(\.\w+)?)/.exec(s) || [];
 return f[1] ||  '';
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.