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#.
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.
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/\">");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With