Can some one help me create a regular expression in C#.net to add target="_blank"
to all <a>
tag links in my content?
If the link already has a target set then replace it with "_blank"
. The purpose is to open all links in my content in a new window.
Appreciate your help
-dotnet rocks
There are a lot of mentions regarding not to use regex when parsing HTML, so you could use Html Agility Pack for this:
HtmlDocument document = new HtmlDocument();
document.LoadHtml(yourHtml);
var links = document.DocumentNode.SelectNodes("//a");
foreach (HtmlNode link in links)
{
if (link.Attributes["target"] != null)
{
link.Attributes["target"].Value = "_blank";
}
else
{
link.Attributes.Add("target", "_blank");
}
}
this will add(or replace if necessary) target='_blank'
to all the anchors in your document.
RegEx.Replace(inputString, "<(a)([^>]+)>", "<$1 target=""_blank""$2>")
It will add target also in those anchor tags which already have target present
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