Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression- add target="blank" to all <a> tag links in my content

Tags:

c#

regex

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

like image 422
dotnetrocks Avatar asked May 10 '10 23:05

dotnetrocks


2 Answers

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.

like image 139
Oleks Avatar answered Oct 13 '22 22:10

Oleks


RegEx.Replace(inputString, "<(a)([^>]+)>", "<$1 target=""_blank""$2>")

It will add target also in those anchor tags which already have target present

like image 28
Avinash Nigam Avatar answered Oct 13 '22 22:10

Avinash Nigam