Get the current URL of my page and add characters to it

Question

Basically I just want to be able to get the current URL of my webpage and add some characters to it.

For example if I'm on: localhost/index.php

I want to put this current url in a variable and add "_en" to it. So it would become: localhost/index_en.php

Like: var url = window.location.pathname

I tried using window.location.pathname and I can get the url but I don't know how to add something to it.

Is there a way to do it in javascript or even in PHP if it's easier ? Thank you!


Show source
| url   | javascript   | php   2017-01-06 22:01 6 Answers

Answers ( 6 )

  1. 2017-01-06 22:01

    Try var url = document.location.pathname; document.location.pathname = url.replace(/(\w+).(\w+)$/, '$1_en.$2');

  2. 2017-01-06 22:01

    You could use javascript string functions to modify the URL, then set the location to your new string.

     var oldURL = "localhost/index.php"
     var newURL = oldURL.substr(0, oldURL.indexOf(".php")) + "_en" + oldURL.substr(oldURL.indexOf(".php"), oldURL.length);
     window.location = newURL;
    

    Here is the link for window.location: https://developer.mozilla.org/en-US/docs/Web/API/Window/location

  3. 2017-01-06 22:01

    This might do it:

    var windowloc = window.location;
    var windowloc=windowloc.substr(0, indexOf("index.php")-4); // changes index.php to index
    windowloc = windowloc+"_en.php";
    
  4. 2017-01-06 23:01

    To fetch the URL of the document use this document.location.href;

    Now replace the . in the URL with _en. using replace and regex expression /\./ for selecting . character.

    Note I am adding _en. as it will replace old . in the URL

    var org_url = document.location.href;
    console.log(org_url);
    
    var new_url = org_url.replace(/\./,'_en.');
    console.log(new_url);

  5. 2017-01-07 00:01

    In order to modify the string, you could remove the last .php by taking a substring, then append _en.php to the resulting substring. This method would be essentially equivalent to inserting a string (_en).

    If you only want to change *.php at the end of the URL, this will work:

    var locStr = window.location;
    var newStr = locStr.substr(0, locStr.length - 4);
    newStr += "_en.php";
    
  6. 2017-01-07 00:01

    In PHP you can use:

    $cur_url = "{$_SERVER['REQUEST_URI']}";
    

    Then just use a replace to the url you want. I would recommend using a replace on .php if you want to add it to the end of the url, as that should always appear only once.

    For example, you could add this after you grab the url:

    $new_url = str_replace('.php', '_en.php', $cur_url);
    
◀ Go back