Skip to content

Instantly share code, notes, and snippets.

@haneytron
Last active July 11, 2023 14:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save haneytron/56abd8c9ecd2a9ed90fa376e657680bf to your computer and use it in GitHub Desktop.
Save haneytron/56abd8c9ecd2a9ed90fa376e657680bf to your computer and use it in GitHub Desktop.
Remove instanceId from query string value and return a new query string. If instanceId is not present, return the original query string.
// NOTE: assumption that query doesn't start with '?'
static string? RemoveInstanceIdFromQueryString(string query)
{
if (string.IsNullOrWhiteSpace(query))
{
return query;
}
// Opting to not use a StringBuilder as a single string concat feels OK re: allocations
// First check if it's the first entry in the query string, and if not it'll be &instanceId
if (query.StartsWith("instanceId"))
{
// It may be the entire query string in which case we return empty string
var nextParamLocation = query.IndexOf('&');
if (nextParamLocation == -1)
{
return "";
}
return query.Substring(nextParamLocation + 1);
}
// If we get here it either isn't in the query string at all or it's part of the query string
// somewhere that isn't the beginning so it'll appear as &instanceId
var locationIndex = query.IndexOf("&instanceId");
if (locationIndex == -1)
{
// It doesn't exist
return query;
}
// Check for it being the very last param
var followingParamIndex = query.IndexOf('&', locationIndex + 1);
if (followingParamIndex == -1)
{
return query.Substring(0, locationIndex);
}
return query.Substring(0, locationIndex) + query.Substring(followingParamIndex);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment