• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1388
  • Last Modified:

Pass URL file name into JavaScript variable

Hello,

We would like to pass the file name found within the URL into a Javascript Variable.

For example if the URL is:

http://www.abc.com/folder/file-something.aspx
Or
http://www.abc.com/folder/folder/file-something.aspx

Then
s.prop5 = 'file-something';

The tricky part is that we need to also include an if statment to populate a default value if the home page is loaded in the URL.

For example if the URL is

http://www.abc.com

Then s.prop5 = 'home';

Thanks :)
 
0
PlumInternet
Asked:
PlumInternet
  • 6
  • 3
1 Solution
 
leakim971PluritechnicianCommented:
Use :


var s.prop5 = 'home';
var start = location.pathname.lastIndexOf("/");
if(start>0) {
   s.prop5 = location.pathname.substr(start+1);
}

Open in new window

0
 
leakim971PluritechnicianCommented:
More info about the location object here : http://www.w3schools.com/jsref/obj_location.asp
Clipboard02.jpg
0
 
PlumInternetAuthor Commented:
Hi leakim971,

Thanks for the snippet, we have dropped it into our dev site: http://beta.mazero.com

and we are receiving an error Expected ';'

Any ideas ?

Thanks
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
leakim971PluritechnicianCommented:
remove "var" in << var s.prop5 = 'home'; >>
0
 
PlumInternetAuthor Commented:
Thanks that has removed the javascript error, but it is passing through the file extension as well ".html" we are hoping to truncate this from the passed variable. As per our example above.

Thanks
0
 
leakim971PluritechnicianCommented:
For example :
s.prop5 = 'home';
var start = location.pathname.lastIndexOf("/");
if(start>0) {
   s.prop5 = location.pathname.substr(start+1).split(".")[0];
}

Open in new window

0
 
leakim971PluritechnicianCommented:
Or :
var end = location.pathname.lastIndexOf(".")
s.prop5 = 'home';
var start = location.pathname.lastIndexOf("/");
var end = location.pathname.lastIndexOf(".");
if(start>0) {
   s.prop5 = location.pathname.substring(start+1, end);
}

Open in new window

0
 
PlumInternetAuthor Commented:
Hi leakim971,

Thanks for your prompt support :)
0
 
leakim971PluritechnicianCommented:
You're welcome my friend! Thanks for the points!
Be careful with the first proposition (accepted solution) if your filename have more than one dot in it : my.file.name.html will return << my >>
0

Featured Post

Vote for the Most Valuable Expert

It’s time to recognize experts that go above and beyond with helpful solutions and engagement on site. Choose from the top experts in the Hall of Fame or on the right rail of your favorite topic page. Look for the blue “Nominate” button on their profile to vote.

  • 6
  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now