Federal09
Federal09

Reputation: 649

String Replace windows location

I tried to replace the windows.location ex:

My windows location is http:// and i need to replace in https, this code return "undefinied" value, why?

<script>
function myFunction()
{
var windost = window.location;
var opens = windost.replace("http","https");
alert(opens);
}
</script>

Upvotes: 0

Views: 1809

Answers (4)

BAD_SEED
BAD_SEED

Reputation: 5056

Use toString() function (or better the href as suggested by Quentin), and combine it with an if to avoid bad replacing.

<script>
    function myFunction()
    {       
        if (window.location.protocol == "http:") {
          var opens = window.location.href.replace("http://", "https://")
          alert(opens);    
        }      
    }
    myFunction()
</script>

Details: Your old replace, even if fixed will make some bad replacing, for example:

  • The location already starts with https (will produce something like httpss://link.com)
  • The location with http word inside the URL

Here is an example.

Upvotes: 0

Myth
Myth

Reputation: 446

try this it will solve your problem

<script>
    function myFunction()
    {
        var windost = window.location.toString();
        var opens = windost.replace("http", "https");
        alert(opens);
    }
</script>

Upvotes: 1

rajesh kakawat
rajesh kakawat

Reputation: 10896

try something like this

function myFunction()
{
    var windost = window.location.href;
    var opens = windost.replace("http","https");
    alert(opens);
}

Upvotes: 0

Quentin
Quentin

Reputation: 943207

location isn't a string, so its replace method doesn't act in the same way as the replacemethod that is available on strings. You want location.href, which is a string.

var windost = location.href;

Upvotes: 3

Related Questions