# Parse and Redirect to uri in Javascript

Example that could be turned into a button to view user's public ftp where initial page is "http://user.school.edu/":

javascript:(function( {
var h,i,t;
h=window.location.hostname;i=h.IndexOf('.school.edu');t=h.substring(0,i);
window.location.assign("ftp://ftp.school.edu/public/"+t
});


Help me refine this idea, please.

-

It can also be written in "one line" using regular expression:

window.location = window.location.hostname.replace(
/^(.*)\.school\.edu$/, "ftp://ftp.school.edu/public/$1"
);


I believe in this case regular expression expresses the intent more clearly than using indexOf and string slicing, though tastes may vary.

-
But then, regular expressions for this task is a bit overkill. – Joseph the Dreamer Feb 20 '13 at 13:17
Regex was not the way I was going, but it does what I want in a geeky-elegant kind of way. I also like that it maintains the replace method so that history is intact. I'm going to run with this. Thank you. – homers Feb 20 '13 at 13:38
(function () {
var h = window.location.hostname;
window.location = 'ftp://ftp.school.edu/public/' + h.substring(0, h.indexOf('.'));
}());

• In JS, you can merge declaration and definition. The compiler takes care of splitting them to declaration and definition during compile.

• Since indexOf returns the first occurrence of a string, you can use the first dot (.) instead of .school.edu. Both will return the same value, but using a single dot is shorter.

• You can change the browser location by assigning a url to window.location than using assign(). Although using assign() might be a more proper way to do it, changing the value of window.location is still shorter

• I JS, single and double quotes don't matter. However, single quotes look cleaner.

• I also prefer the comma-separated var notation since it will save you retyping var every time. However, don't ever forget the commas.

-
Both will return the same value It won't, if you have address like http://foo.bar.school.edu/ – Lie Ryan Feb 20 '13 at 12:21
@LieRyan look at the OP's post. The url pattern given was user.school.edu and nothing more. – Joseph the Dreamer Feb 20 '13 at 12:35
The comma-separated approach does look much cleaner. – homers Feb 20 '13 at 13:36