By Philip Miseldine

Working with HTML markup

By Philip Miseldine

This happened to me recently. I needed a way of highlighting keywords in a chunk of HTML for when users visited the site through Google. In this way, you can help your users locate the information they’ve searched for in Google quickly.

However, a simple string.Replace function wouldn’t cut the mustard. Obviously, it would also replace any mention of a keyword in the HTML markup too, and so would kill links or images.

For example, take the keyword “sitepoint” and I wish to replace it with some HTML “sitepoint“. If my image name had “sitepoint” in it, I’d end up with sitepoint.jpg”>. Not what I want.

So, I hacked together a little function to first remove all the HTML tags in a string, and then replace them once the replacement has been made. I hope it is of some use, fellow readers:

private string highlightText(string text, string keyword, string highlightColour) {
//ok strip the tags, but keep them safe
System.Collections.ArrayList a = new
string temp = text;
//ok, find an < while (temp.IndexOf("<") != -1) { int start = temp.IndexOf("<"); int end = temp.IndexOf(">");
//ok. remove
temp = temp.Substring(0,start)+"

The most important and interesting stories in tech. Straight to your inbox, daily. Get Versioning.
Login or Create Account to Comment
Login Create Account