Page 1 of 1

getting part of a url

Posted: Fri Oct 28, 2005 9:35 am
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

Posted: Fri Oct 28, 2005 9:55 am
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]);

Posted: Fri Oct 28, 2005 11:29 am
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>

Posted: Fri Oct 28, 2005 2:30 pm
by elecktricity
just being curious but would you do this with php?

Posted: Sat Oct 29, 2005 9:53 am
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.