1

How can I trim a string by a whole string instead of a list of single characters?

I want to remove all   and whitespaces at beginning and end of an HTML string. But method String.Trim() does only have overloads for set of characters and not for set of strings.

0

4 Answers 4

8

You could use HttpUtility.HtmlDecode(String) and use the resultant as an input for String.Trim()

HttpUtility.HtmlDecode on MSDN
HttpServerUtility.HtmlDecode on MSDN (a wrapper you can access through the Page.Server property)

string stringWithNonBreakingSpaces;
string trimmedString =  String.Trim(HttpUtility.HtmlDecode(stringWithNonBreakingSpaces));

Note: This solution would decode all the HTML strings in the input.

Sign up to request clarification or add additional context in comments.

3 Comments

I would also have done that :-) If @brgerner does not want to decode and re-encode the string, a Regex would also do the trick.
Yes, true I agree I would have gone the regex route too or even a String.Replace. Made me add the side note :)
@ABKolan Thanks, that works (with HttpUtility.HtmlDecode(String)) for  . Is there also a method to trim \n and \r?
2

The Trim method removes from the current string all leading and trailing white-space characters by default.

Edit: Solution for your problem AFTER your edit:

string input = @"  &nbsp; <a href='#'>link</a>  &nbsp; ";
Regex regex = new Regex(@"^(&nbsp;|\s)*|(&nbsp;|\s)*$");
string result = regex.Replace(input, String.Empty);

This will remove all trailing and leading spaces and &nbsp;. You can add any string or character group to the expression. If you were to trim all tabs too the regex would simply become:

Regex regex = new Regex(@"^(&nbsp;|\s|\t)*|(&nbsp;|\s|\t)*$");

3 Comments

@brgerner wants to remove the text "&nbsp;" from the string
I edited my question: my first version swallowed the text: &nbsp;.
@Till +1 If he needs &nbsp; in the middle, thats the answer
1

Not sure if this is what you're looking for?

   string str = "hello &nbsp;";
   str.Replace("&nbsp;", "");
   str.Trim();

1 Comment

This will replace everywhere, not at the beginning
1

Use RegEx, as David Heffernan said. It is rather easy to select all spaces at the start of string: ^(\ |&nbsp;)*

2 Comments

He wants to trim string both at the start and at the end
This is just a hint, not complete 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.