Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

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.

share|improve this question
add comment

2 Answers 2

up vote 4 down vote accepted

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.

share|improve this answer
    
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
add comment
(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.

share|improve this answer
    
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
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.