Q:

Regular expression javascript change value of param in url

Using regex, I want to write a function that will replace a get parameter with a new value. 
For example the following will replace pin with a new value. If the parameter doesn't exist, we will add it to the url. 
  myfunc('http://localhost:8080/signup.html?first_name=Ray&username=ray%2B1%40gmail.com&bid=257&pin=1908554354&provisionalId=258&last_name=Ya&debug=true#/signupnew', 'pin', 'AAAAAAA');

// returns http://localhost:8080/signup.html?first_name=Ray&username=ray%2B1%40gmail.com&bid=257&pin=AAAAAAA&provisionalId=258&last_name=Ya&debug=true#/signupnew

A:

You can define the function like this :
function myfunc(url, name, value) {
   return url.replace(new RegExp("(\\?|&)"+name+"=.*?($|&)"), '$1'+name+'='+value+'$2')
}

This suppose the name and values are yet escaped for an URL.
Demonstration (open the console to see the result)

