Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Removing html tag from a string and adding a new line

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 –

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading