I have this url: http://localhost/example/product/illimani/?lang=fr?lang=fr
Now I want to remove this ?lang=frbecause this already exists from url.
I hope you understand my question.
If already exists remove ?lang=fr else don't.
I have this url: http://localhost/example/product/illimani/?lang=fr?lang=fr
Now I want to remove this ?lang=frbecause this already exists from url.
I hope you understand my question.
If already exists remove ?lang=fr else don't.
You can use:
url.replace(/(\?lang=fr)+/g, '?lang=fr')
To replace multiple occurrences of ?lang=fr with just one.
You could use something like
var re = /(\?[\w|=]*)+\1/;
var str = 'http://localhost/example/product/illimani/?lang=fr?lang=fr?lang=fr';
str.match(re);
The re should be pruned to include URL parameters in a more generalised format. This will only replace consecutive duplicates. If you want to find dis-joint duplicates, then you ought to use a programming language IMHO. You can then replace it with the special code $1 backreference.
You can do a simple replace if you just want to handle the one scenario you described:
var new_url = url.replace(/(\?lang=fr)+/g, '?lang=fr');
To handle all repeated variables, try this instead:
var new_url = url;
var temp = '';
while( temp != new_url) { // need this in case params are out of order
temp = new_url;
new_url = temp.replace(/([&?])([^=&?]+=[^=&?]+)(.*)\2/g, '$1$2$3');
}
new_url = new_url.replace(/[&?]+/g, '&').replace(/&+/, '?').replace(/&$/, '');
For example, this would turn http://localhost/example/product/illimani/?foo=bar&lang=fr?foo=bar&lang=fr into http://localhost/example/product/illimani/?foo=bar&lang=fr