My use case for this requirement was that users can add text on a web site and could include links (a tags). I want all these links
to open a new window when clicked on. So I needed to add a target="_blank" to all the a tags in the text.
My first idea was to use pure Regular Expressions, but I couldn't figure out how to use the negative lookahead feature, I needed
this because I can't simple add a target="_blank" to each a tag, what if it already has one?
So instead I am using a simple Regex to find the appropriate tags and then use a MatchEvaluator, which is a very cool
feature of the .Net regular expression class. It allows you to compute the replacement string in a method for each
match.
public class HtmlHelper { string _attrib = string.Empty; public string AddAttribute(string source, string tagName, string attrib) { _attrib = attrib; string term = "<" + tagName + " [^>]+>"; Regex r = new Regex(term, RegexOptions.IgnoreCase); MatchEvaluator myEvaluator = new MatchEvaluator(this.ProcessMatch); return r.Replace(source, myEvaluator); } private string ProcessMatch(Match m) { string tag = m.Value; if (tag.IndexOf(_attrib) == -1) { tag = tag.Replace(">", " " + _attrib + ">"); } return tag; } }This can then be used like this:
HtmlHelper helper = new HtmlHelper(); htmlText = helper.AddAttribute(htmlText, "a", "target=\"_blank\"");