getting part of a url

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
taldos
Forum Commoner
Posts: 39
Joined: Mon Aug 23, 2004 8:47 am
Location: Philadelphia

getting part of a url

Post by taldos »

If I had the following url

http://www.somename.com/secure/default.aspx

I would like to use javascript to get only 'default.aspx'

I know that I can use window.location to get the full url and location.pathname will give me '/secure/default.aspx' Any clues as to how I go about getting only the last part.

Thanks
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post by Chris Corbyn »

Regex :)

Code: Select all

var someURL = 'http://foo.bar/secure/default.apsx';

var re = /\/([^\/]+)$/;

var matches = someURL.match(re);

alert(matches[1]);
User avatar
Burrito
Spockulator
Posts: 4715
Joined: Wed Feb 04, 2004 8:15 pm
Location: Eden, Utah

Post by Burrito »

or you could just split the string and grab the last item in the array:

Code: Select all

<script>
string = "http://www.someserver.com/somefolder/somepage.php";
string = string.split("/");
string = string[string.length -1];
alert(string);
</script>
User avatar
elecktricity
Forum Contributor
Posts: 128
Joined: Sun Sep 25, 2005 8:57 pm
Location: Trapped in my own little world.
Contact:

Post by elecktricity »

just being curious but would you do this with php?
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post by Chris Corbyn »

elecktricity wrote:just being curious but would you do this with php?
It works with either but using PHP is probably a better option yes.
Post Reply