开发者

Efficiently Adding/Removing a directory in current URL w/JavaScript

I'm a JavaScript beginner and managed to piece together to following code. It gets the job done, but I'd like to keep learning and I'm wondering if there's a more efficient/elegant way to accomplish the task.

I have an English site translated 开发者_C百科to Italian. The translated pages have identical file names, and reside in the directory 'IT'. So I put a link on every page that triggers a script to add /IT/ while maintaining the rest of the current URL. On the Italian pages a complementary script removes the directory to return to the English page.

Here's the code:

(note: my part of the site resides at domain.com/site/ in case you're wondering why the code doesn't add the /IT/ directory at the root level.)

function italian(){
  var str;
  var str = document.URL;
  arr = str.split("/");
  var URLparts;
  var URLparts = arr.length;
  var count;
  var count = 0;

  var newURL;
  newURL = "";


  while (count < URLparts){
    newURL = newURL + arr[count];
    count = count + 1;

      if (count < URLparts){
        newURL = newURL + "/";
      }

      switch(count){
        case 4:
        newURL = newURL + "IT/";
        break;
      }

    }

  window.location = newURL;

}

What can I work on to improve it? I'm certainly willing to put in the leg work. If you can point me in the direction of things to research, I'm happy to take it from there.

Thanks!


A slightly more concise version might use a regex to insert/remove the /IT/ part from the url, i.e:

function italian() {
    # make domain.com/site/ -> domain.com/site/IT/
    window.location = document.URL.replace(/site\//, "site/IT/")
}


Depends a bit on which serverside language you use, but most languages have good i18n (Internationalization) support. That way you can create multi language sites within one layout. Advantage of this is that you don't have to change your code twice if something changes.

I realize my answer is not really an answer to improve your script, but I think it would be a good improvement to your complete site.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜