views:

69

answers:

3

How do I make a Javascript regular expression that will take this string (named url_string):

http://localhost:3000/new_note?date1=01-01-2010&date2=03-03-2010

and return it, but with the value of the date1 parameter set to a new date variable, which is called new_date_1?

+1  A: 

There are better ways to manipulate URL than regex, but a simple solution like this may work:

after = before.replace(/date1=[\d-]+/, "date1=" + newDate);

[\d-]+ matches a non-empty sequence of digits and/or dashes. If you really need to, you can also be more specific with e.g. \d{2}-\d{2}-\d{4}, or an even more complicated date regex that rejects invalid dates, etc.

Note that since the regex makes the "date1=" prefix part of the match, it is also substituted in as part of the replacement.

polygenelubricants
A: 

It's messy, but:

var url_string = "http://localhost:3000/new_note?date1=01-01-2010&date2=03-03-2010";
var new_date_1 = "01-02-2003";

var new_url_string = url_string.replace(/date1=\d{2}-\d{2}-\d{4}/, "date1="+new_date_1);
/* http://localhost:3000/new_note?date1=01-02-2003&date2=03-03-2010 */

There must be a proper URL parser in JS. Have a Google.

chigley
A: 
url.replace(/date1=[0-9-]{10}/, "date1=" + new_date_1);
Edgar Bonet