I have a query string that I want to get a value from. I want to extract a piece of text from the string and display it but I can’t quite figure it out.
This is the query string:
utm_source=google&utm_medium=cpc&utm_campaign=Microsoft&gad_source
So I want to extract the piece of text after “utm_campaign” from the string and display it. In this case I will display the text “Microsoft”.
How can I do this?
Any help is appreciated.
2
As mentioned in one of the comments, using HttpUtility.ParseQueryString
is a an appropriate solution as it is specifically made for parsing query strings.
You can use it like this:
var queryString = "utm_source=google&utm_medium=cpc&utm_campaign=Microsoft&gad_source=Chicken%20Giblets";
var queryStringData = HttpUtility.ParseQueryString(queryString);
var campaignValue = queryStringData.Get("utm_campaign");
1
This is pretty ugly but a very basic example using string.Split:
string a = "utm_source=google&utm_medium=cpc&utm_campaign=Microsoft&gad_source";
string[] pars = a.Split('&');
foreach (string par in pars)
{
string[] parts = par.Split('=');
if (parts[0] == "utm_campaign")
return parts[1];
}
This splits the string by “&” into sections of “name=value”. Then splits those strings in the loop by “=” to separate the name from the value.
2