Reputation: 649
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
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:
Here is an example.
Upvotes: 0
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
Reputation: 10896
try something like this
function myFunction()
{
var windost = window.location.href;
var opens = windost.replace("http","https");
alert(opens);
}
Upvotes: 0
Reputation: 943207
location
isn't a string, so its replace
method doesn't act in the same way as the replace
method that is available on strings. You want location.href
, which is a string.
var windost = location.href;
Upvotes: 3