• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1396
  • 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
Get expert help—faster!

Need expert help—fast? Use the Help Bell for personalized assistance getting answers to your important questions.

 
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
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Get expert help—faster!

Need expert help—fast? Use the Help Bell for personalized assistance getting answers to your important questions.

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