Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add string after a specified string

Tags:

string

c#

Say I have the following HTML string

<head>

</head>

<body>
<img src="stickman.gif" width="24" height="39" alt="Stickman">
<a href="http://www.w3schools.com">W3Schools</a>
</body> 

I want to add a string in between the <head> tags. So the final HTML string become

<head>
<base href="http://www.w3schools.com/images/">
</head>

<body>
<img src="stickman.gif" width="24" height="39" alt="Stickman">
<a href="http://www.w3schools.com">W3Schools</a>
</body> 

So I have to search for the first occurrence of the <head> string then insert <base href="http://www.w3schools.com/images/"> right after.

How do I do this in C#.

like image 644
PutraKg Avatar asked Dec 18 '25 19:12

PutraKg


2 Answers

So why not just do something easy like

myHtmlString.Replace("<head>", "<head><base href=\"http://www.w3schools.com/images/\">");

Not the most elegant or expandable, but satisfies the conditions of your question.

like image 175
dav_i Avatar answered Dec 20 '25 08:12

dav_i


Another way of doing this:

string html = "<head></head><body><img src=\"stickman.gif\" width=\"24\" height=\"39\" alt=\"Stickman\"><a href=\"http://www.w3schools.com\">W3Schools</a></body>";
var index = html.IndexOf("<head>");

if (index >= 0)
{
     html = html.Insert(index + "<head>".Length, "<base href=\"http://www.w3schools.com/images/\">");
}
like image 21
gzaxx Avatar answered Dec 20 '25 07:12

gzaxx



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!