0

I am trying to replace the second instance only of of the '&' character or replace all instances of '&' after the first '&' in the URL www.website.com/--Inventory&vt=test%20&%20unit

so far I've been using:

var url = window.location.toString();
window.location = url.replace(/&/, '%26');
window.location.reload(false);

but that replaces all the '&' characters. any ideas are appreciated. thanks!

wallrouse
  • 116
  • 1
  • 13
  • you want to keep the first one and replace only the second and let anything there after stay the same as '&' like the first instance or do you only want the first instance to remain an '&' and everything else '%26' – TrojanMorse Jan 03 '17 at 21:44
  • @ToreanJoel yeah I think having the first instance to remain an '&' and everything else '%26' is more of what I was asking – wallrouse Jan 03 '17 at 21:51
  • The provided url does not look valid to me I always thought that it should have a ? before any &'s for example: www.website.com/--Inventory?vt=tes&vt=unit or www.website.com/--Inventory?vt=tes%26unit – Gavin Harrison Jan 03 '17 at 21:53
  • You almost certainly want to do this with the `encodeURIComponent` method, not hand massage special characters in URLs – Andy Ray Jan 03 '17 at 22:23

3 Answers3

1

You can select the position of the 2nd & character in your url by passing the (index of first & character) + 1 as 2nd parameter to indexOf function.

2nd argument of the indexOf function defines the index of the string from which character should be searched from.

learn more here

(In this case, the search starts from the 1 + index of first & character)

var position = url.indexOf("&", url.indexOf("&") + 1);

Now you can replace the character at the position as follows:

url=url.substr(0, position) + '%26' + url.substr(position + 1);

var url = "www.website.com/--Inventory&vt=test%20&%20unit";

var position = url.indexOf("&", url.indexOf("&") + 1);

url=url.substr(0, position) + '%26' + url.substr(position + 1);

console.log(url)
Nadir Laskar
  • 4,012
  • 2
  • 16
  • 33
0

Dirty, but works...

var url = window.location.toString();
var explode = url.split("&");
url = "";
for(int i=0; i<explode.length; i++) {
    url+=exlode[i];
    if(i!=explode.length-1) {
        if(i==1){
            url+="%26";
        } else {
            url+="&";
        }
    }
}
Autumn Leonard
  • 514
  • 8
  • 22
0

String.prototype.replaceAt=function(index, character) {
    return this.substr(0, index) + character + this.substr(index+1, this.length);
}

var url="www.website.com/--Inventory&vt=test%20&%20unit";
url=url.split("").reverse().join("");
var index=url.indexOf("&");
url=url.replaceAt(index,"62%");
url=url.split("").reverse().join("");
console.log(url);

and result is:

www.website.com/--Inventory&vt=test%20%26%20unit

hubman
  • 149
  • 1
  • 15