bappa147
bappa147

Reputation: 539

How to replace a url in javascript?

I want to replace a URL with another while loading. I have written the code below.

<script type="text/javascript">
    var executed = false;
     if (!executed) {
        executed = true;
        window.location.href = window.location.pathname + '?'+'bc';
            }
</script>

But it's not working correctly. It's loading again and again. It doesn't stop.

Upvotes: 0

Views: 58

Answers (2)

ssbb
ssbb

Reputation: 2025

Just you variables resets after page reload. Try to check GET params like this:

if (window.location.search.indexOf('?bc') === -1) {
  window.location.href = window.location.pathname + '?bc';
}

Upvotes: 1

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324640

The executed variable is not kept when going to the new page. Even if it were, var executed = false just sets it to false again :p

Try this instead:

if( !window.location.search.match(/\?bc$/)) {
    window.location.href = window.location.pathname+"?bc";
}

Upvotes: 3

Related Questions