user2065483
user2065483

Reputation: 1225

jQuery, regex that matches a query string

I have this URL and I want to match the test=dahsdhajd part in order to remove it using replace();

http://www.mysite.com?test=dhasjdhja&src=list

I could use this regex:

var regex = /test=.+&/;
var url = window.location.href;
var newUrl = url.replace(regex, "");

This would work just fine, giving me:

http://www.mysite.com?test=dhasjdhja

The problem is, I need to make the regex match the test = dshajdhajd when I do not have another query string after it:

http://www.mysite.com?test=dhasjdhja

My current regex won't match the above, because there is no "&" Also, in this case, I need a way to remove the question mark also - so the regex should match it too.

How can I do it?

Upvotes: 1

Views: 564

Answers (1)

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324640

I would suggest working with the character behind it, like so:

.replace(/([?&])test(?:(?=&)|=[^&]*)/,"$1")

This works fine with the end of the string, and allows it to not affect something like ?anothertest=derp

EDIT: Changed it a bit to add support for an empty or boolean parameter.

Upvotes: 1

Related Questions