Home > Blockchain >  Removing html tag from a string and adding a new line
Removing html tag from a string and adding a new line

Time:07-28

I am using regex to remove html tags from my string

Air Receiver <br /> Pressure Washer <br />Vehicle Lift<br />100T Crane Attachment<br />

which is working well.

ViewBag.PlantDetails =
    Regex.Replace(QuoteDetails.PlantDetails, @"<[^>] >|&nbsp;", " ").Trim();

which returns the following string -

Air Receiver Pressure Washer Vehicle Lift 100T Crane Attachment

My question is, is there a way to add a new line to the string so that it shows like below?

Air Receiver
Pressure Washer
Vehicle Lift
100T Crane Attachment

CodePudding user response:

So if <br />, and exactly that (with the space and everything) is the only HTML tag that you'll encounter, then Regex is overkill. Use a simple string replace.

var input = "Air Receiver <br /> Pressure Washer <br />Vehicle Lift<br />100T Crane Attachment<br />";
var output = input.Replace("<br />", Environment.NewLine);

In your example, you have spaces sometimes on either end of the break, so trim it if you want.

output = string.Join(Environment.NewLine, output.Split(Environment.NewLine).Select(x => x.Trim()));

If you really want to use Regex, it can be used to match the break and surrounding whitespace.

var output = Regex.Replace(input, @"\s*<br \/>\s*", Environment.NewLine);
  • Related