views:

46

answers:

5

I have the following RegEx to replace the entire querystring for a string with a new one:

"http://www.google.com?bar=1".replace(/\?.*/, "?foo=2")

This works only if there is a querystring. The following will not work:

"http://www.google.com".replace(/\?.*/, "?foo=2")

How do I make the RegEx match both situations?

+2  A: 

No use for regex to me. Check if there is a ? - if not append your querystring, otherwise drop the old query string first. KISS.

Alexander Gessler
A: 

This should work, but I'm not sure exactly what you are trying to do, I can't remember the syntax for regex in javascript so the replacestring is in python syntax but it should give you the idea.. You are matching an excaped "?" when you do "\?" so its not going to match the second since there is no "?" in the string.

/(.*?google.com)(.*?)/  

replacestring = '\\1'+'?foo=2'
Rick
this doesn't return valid results.
Russ Bradberry
you need to change the syntax for javascript, I don't use js regex but its the same in all languages just different syntax, each "()" in the regex is one area to be replaced, my replacestring is saying: "keep first () the same" and replace second "()" with '?foo=2' ... sorry I can't be of more help to give exact syntax I just don't have the time at the moment to research it
Rick
what i was trying to do was append a querystring if one did not exist and replace it if one does. this doesn't seem to accomplish that.
Russ Bradberry
+3  A: 

Say or end of string:

|$

replace(/\?.*|$/, "?foo=2")
David Dorward
this is perfect and exactly what i was asking for. in my eyes, this is much more simple that checking the string for a question mark then running a regex on it.
Russ Bradberry
+3  A: 

Avoid string/regex hacking for manipulating URLs in JS. There's a perfectly good URL parser built into every browser, and you can get access to it from any link element:

var a= document.createElement('a');
a.href= 'http://www.google.com/?bar=1';
a.search= '?foo=2';
alert(a.href); // http://www.google.com/?foo=2
bobince
+1  A: 

Capture the host and replace all else with the desired querystring.

url.replace(/([^?]+).*/, "$1?querystring");
Anurag