Coding Cookbook/Change Query Parameter

Change parameters in an URL querystring (for example "param1=foo&param2=bar").

VBScript solution

edit
function ChangeQueryParameter (Query, Parameter, Value)
  
  dim sTemp
  dim SubstringStart ' Starting position of Parameter within Query
  dim SubstringEnd   ' Ending position of Parameter within Query
  
  if (Query = "") then
    ChangeQueryParameter = ""
  else
    sTemp = "&" & Query
    ' Let every parameter start with '&'

    SubstringStart = InStr (LCase(sTemp), "&" & LCase(Parameter) & "=")
    if (SubstringStart = 0) then
      ' Parameter was not yet included
      ChangeQueryParameter = sTemp
    else
      ' Parameter already existed
      ChangeQueryParameter = Left (sTemp, SubstringStart-1)    
      SubstringEnd = InStr (SubstringStart+1, sTemp, "&")
      if not (SubstringEnd = 0) then
        ' Parameter was not last in query
        ChangeQueryParameter = ChangeQueryParameter & Mid(sTemp, SubstringEnd)
        end if
      end if
    end if

  if not (Value = "") then _
    ChangeQueryParameter = ChangeQueryParameter & "&" & Parameter & "=" & Value
    ' If an empty value has been giving, the parameter will be removed

  if not (ChangeQueryParameter = "") then _
    ChangeQueryParameter = Mid(ChangeQueryParameter, 2)

  end function

strQuery = "param1=foo&param2=bar"
strQuery = ChangeQueryParameter( strQuery, "param1", "foobar" )
  ' Result: "param1=foobar&param2=bar"
strQuery = ChangeQueryParameter( strQuery, "param1", "" )
  ' Result: "param2=bar"