-2

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
  • 3
    This string looks like a URL search/query. You could use HttpUtility.ParseQueryString to get a name value collection. Commented Jun 7, 2024 at 8:13
  • 2
    Be aware that HttpUtility.ParseQueryString will decode encoded stuff. That is presumable wanted but you should know. en.wikipedia.org/wiki/UTM_parameters Commented Jun 7, 2024 at 8:15

2 Answers 2

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");
Sign up to request clarification or add additional context in comments.

1 Comment

Freexel: be aware that campaignValue could still be null, here (if "utm_campaign" happens to not be in the string).
0

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.

3 Comments

It has a bug, though: if "utm_campaign" weren't contained, then this would throw an index out of bounds for the last item.
Note: very basic example - not intended as a final solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.