SamJolly
SamJolly

Reputation: 6477

Simple way to replace specific HTML substring in HTML?

I have

OldPattern = <div style="page-break-after: always"><span style="display: none;">&nbsp;</span></div>

in some master Html.

I want to replace with:

NewPattern = <br> <br style="page-break-after: always;" />

I believe I can do something like:

NewHtml = OldHtml.Replace(OldPattern, NewPattern)

Of course the assignment will not work due to the double quotes etc. This is where I get stuck.

Appreciate any help.

Upvotes: 1

Views: 111

Answers (4)

Izzy
Izzy

Reputation: 6866

You could also do

string OldPattern = string.Format("<div style=\"{0}\"><span style=\"{1}\"</span></div>", "page-break-after: always", "display: none;");
string NewPattern = string.Format("<br><br style=\"{0}\"/>","page-break-after: always;");

NewHtml = OldHtml.Replace(oldPattern, newPattern);

Upvotes: 1

Thorarins
Thorarins

Reputation: 1904

You can also use @ in front of a string and use "" for escaping , wich makes the code more readable

   OldPattern = @"<div style=""page-break-after: always""><span style=""display: none;"">&nbsp;</span></div>" 
   NewPattern = @"<br> <br style=""page-break-after: always;"" />"
   NewHtml = OldHtml.Replace(OldPattern, NewPattern)

Upvotes: 1

Fᴀʀʜᴀɴ Aɴᴀᴍ
Fᴀʀʜᴀɴ Aɴᴀᴍ

Reputation: 6251

You need to escape double quotes inside a string. You can do it in the following ways:

In normal strings:

Use the backslash (\) character before the character to be escaped:

string escaped = "\"Hello\"";

This will assign "Hello" to escaped.

In verbatim literals:

Use two double quotes within the string like this:

string escaped = @"""Hello""";

This will assign "Hello" to escaped.

In your case:

OldPattern = "<div style=\"page-break-after: always\"><span style=\"display: none;\">&nbsp;</span></div>"
NewPattern = "<br> <br style=\"page-break-after: always;\" />"
NewHtml = OldHtml.Replace(OldPattern, NewPattern)

Upvotes: 2

Thomas Ayoub
Thomas Ayoub

Reputation: 29431

You need to escape your quotes like so \". This works well:

string oldPattern = "<div style=\"page-break-after: always\"><span style=\"display: none;\">&nbsp;</span></div>";
string newPattern = "<br> <br style=\"page-break-after: always;\" />";
NewHtml = OldHtml.Replace(oldPattern, newPattern);

Upvotes: 2

Related Questions