views:

1234

answers:

1

I have a set of links in header.asp which is included on every page; these links have their href attribute set to whatever the current page is plus a linkID param. Sometimes the page the link references will have query string params, but other times it won't. If the current page URL contains the linkID param already I need to replace it, otherwise I need to add it to the current URL.

I am concatenating Request.ServerVariables("SCRIPT_NAME") and Request.ServerVariables("QUERY_STRING") into a variable pagename to get the current page URL. Unfortunately, I'm using classic ASP/VBScript.

I think I need to use reg ex but am not expert in it, especially not in classic ASP. The problem comes when I need to replace the element as the linkID param's value can vary so the simple Replace method won't work.

Any help is appreciated.

+1  A: 

You can check if the parameter is already in the querystring Request.QueryString("linkID") = "" and simply append if it isn't and use a function to update the value if it is there. Something like this will be fine as long as you don't have a massive number of parameters and you're not having to optimise massively but then you would probably not be using ASP.

Function updateQueryStringParam(key, value)

  Dim qs, x

  For Each x In Request.QueryString
    qs = qs & x & "="

    If x = key Then
      qs = qs & value & "&"
    Else
      qs = qs & Request.QueryString(x) & "&"
    End If
  Next

  If Len(qs) > 0 Then
    If Right(qs, 1) = "&" Then
      qs = Left(qs, Len(qs)-1)
    End If
  End If

  updateQueryStringParam = qs

End Function

You could create another function call for the check and then update using the function above;

Function setQueryStringValue(key, value)

  Dim qs

  If Request.QueryString(key) = "" Then
    If Len(qs) > 0 Then
      qs = qs & "&"
    End If
    qs = key & "=" & value
  Else
    qs = updateQueryStringParam(key, value)
  End If

  setQueryStringValue = qs

End Function
Dave Anderson
Thank you, this worked a treat.
Rich