200

I feel kind of dumb posting this when this seems kind of simple and there are tons of questions on strings/characters/regex, but I couldn't find quite what I needed (except in another language: Remove All Text After Certain Point).

I've got the following code:

[Test]
    public void stringManipulation()
    {
        String filename = "testpage.aspx";
        String currentFullUrl = "http://localhost:2000/somefolder/myrep/test.aspx?q=qvalue";
        String fullUrlWithoutQueryString = currentFullUrl.Replace("?.*", "");
        String urlWithoutPageName = fullUrlWithoutQueryString.Remove(fullUrlWithoutQueryString.Length - filename.Length);

        String expected = "http://localhost:2000/somefolder/myrep/";
        String actual = urlWithoutPageName;
        Assert.AreEqual(expected, actual);
    }

I tried the solution in the question above (hoping the syntax would be the same!) but nope. I want to first remove the queryString which could be any variable length, then remove the page name, which again could be any length.

How can I get the remove the query string from the full URL such that this test passes?

10 Answers 10

340

For string manipulation, if you just want to kill everything after the ?, you can do this

string input = "http://www.somesite.com/somepage.aspx?whatever";
int index = input.IndexOf("?");
if (index >= 0)
   input = input.Substring(0, index);

Edit: If everything after the last slash, do something like

string input = "http://www.somesite.com/somepage.aspx?whatever";
int index = input.LastIndexOf("/");
if (index >= 0)
    input = input.Substring(0, index); // or index + 1 to keep slash

Alternately, since you're working with a URL, you can do something with it like this code

System.Uri uri = new Uri("http://www.somesite.com/what/test.aspx?hello=1");
string fixedUri = uri.AbsoluteUri.Replace(uri.Query, string.Empty);
Sign up to request clarification or add additional context in comments.

6 Comments

Or would it be the last / ?
Oh, yeah, re-read that. He can do LastIndexOf("/") in that case.
Lets says that my input string is always like http://www.somesite.com/somepage.aspx and I just want to fetch the last value (somepage.aspx or abc.xml) from it. Then what to do... ???
@gsvirdi, in that case, you may load that URL into Uri uri, and then access uri.Segments. That will return an array, and "somepage.aspx" will be the last item.
Its shorter single line equivalent is: input = input.Substring(0, input.LastIndexOf("/")+1);
|
152

To remove everything before the first /

input = input.Substring(input.IndexOf("/"));

To remove everything after the first /

input = input.Substring(0, input.IndexOf("/") + 1);

To remove everything before the last /

input = input.Substring(input.LastIndexOf("/"));

To remove everything after the last /

input = input.Substring(0, input.LastIndexOf("/") + 1);

An even more simpler solution for removing characters after a specified char is to use the String.Remove() method as follows:

To remove everything after the first /

input = input.Remove(input.IndexOf("/") + 1);

To remove everything after the last /

input = input.Remove(input.LastIndexOf("/") + 1);

1 Comment

Be aware that these will all throw an exception if the string doesn't contain a "/" at all. Obviously this won't be an issue if you're working with hard-coded strings as in the original question, but in most cases, you'll want to take that into consideration.
18

Here's another simple solution. The following code will return everything before the '|' character:

if (path.Contains('|'))
   path = path.Split('|')[0];

In fact, you could have as many separators as you want, but assuming you only have one separation character, here is how you would get everything after the '|':

if (path.Contains('|'))
   path = path.Split('|')[1];

(All I changed in the second piece of code was the index of the array.)

Comments

4

The Uri class is generally your best bet for manipulating Urls.

1 Comment

An example of link would be nice.
1

I second Hightechrider: there is a specialized Url class already built for you.

I must also point out, however, that the PHP's replaceAll uses regular expressions for search pattern, which you can do in .NET as well - look at the RegEx class.

Comments

1

To remove everything before a specific char, use below.

string1 = string1.Substring(string1.IndexOf('$') + 1);

What this does is, takes everything before the $ char and removes it. Now if you want to remove the items after a character, just change the +1 to a -1 and you are set!

But for a URL, I would use the built in .NET class to take of that.

Comments

1

Request.QueryString helps you to get the parameters and values included within the URL

example

string http = "http://dave.com/customers.aspx?customername=dave"
string customername = Request.QueryString["customername"].ToString();

so the customername variable should be equal to dave

regards

Comments

0

you can use .NET's built in method to remove the QueryString. i.e., Request.QueryString.Remove["whatever"];

here whatever in the [ ] is name of the querystring which you want to remove.

Try this... I hope this will help.

Comments

0

You can use this extension method to remove query parameters (everything after the ?) in a string

public static string RemoveQueryParameters(this string str)
    {
        int index = str.IndexOf("?");
        return index >= 0 ? str.Substring(0, index) : str;
    }

Comments

0

Here is a method that provides some options re what to keep.

        /// <summary> Keep start of string until find "match".
        /// If "match" not found, keep entire string.
        /// If "includeMatch", "match" is kept in result, otherwise is excluded.
        /// If "lastMatch", and there are multiple "matches", the LAST one is used as the match.
        /// </summary>
        static public string KeepUntil(string s, string match, bool includeMatch = false, bool lastMatch = false)
        {
            if (string.IsNullOrEmpty(s) || string.IsNullOrEmpty(match))
                return s;

            int index = (lastMatch ? s.LastIndexOf(match) : s.IndexOf(match));
            if (index < 0)
                return s;

            if (includeMatch)
                index += match.Length;
            return s.Substring(0, index);
        }

Usage:

To remove everything after last "/":

var currentFullUrl = "http://localhost:2000/somefolder/myrep/test.aspx?q=qvalue";
var result = KeepUntil(currentFullUrl, "/", includeMatch: true, lastMatch: true);
var expected = "http://localhost:2000/somefolder/myrep/";

Comments

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.