1

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.

1
  • That gets there from another page, you should find where it originates and use a conditional to check if it would be duplicating before changing pages. Commented Jan 17, 2014 at 6:15

3 Answers 3

1

You can use:

url.replace(/(\?lang=fr)+/g, '?lang=fr')

To replace multiple occurrences of ?lang=fr with just one.

Sign up to request clarification or add additional context in comments.

3 Comments

Where I pass my url string?
This will not replace the string if there is something in between the two occurrences.
@Aashray - Yeah. I hadn't considered that possibility. :)
0

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.