有人能帮我在C#.net中创建一个正则表达式,将target="_blank"
添加到我内容中的所有<a>
标记链接吗?
如果链接已有目标集,则将其替换为"_blank"
。其目的是在新窗口中打开“我的内容”中的所有链接。
感谢您的帮助
-dotnet岩石
发布于 2011-04-23 14:59:44
有很多关于的提及,所以您可以使用Html Agility Pack:
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");
}
}
这将向文档中的所有锚点添加(或在必要时替换) target='_blank'
。
发布于 2011-07-06 17:33:28
RegEx.Replace(inputString, "<(a)([^>]+)>", "<$1 target=""_blank""$2>")
它还将在那些已经存在目标锚点标签中添加目标
发布于 2015-03-27 06:58:48
我使用了一个扩展方法,类似于Alex展示的方法。方法:
// Return the input string with all parsed HTML links having the "target" attribute set to specified value
// Links without a target attribute will have the attribute added, existing attributes values are updated
public static string SetHtmlLinkTargetAttribute(this string inputHtmlString, string target)
{
var htmlContent = new HtmlDocument();
htmlContent.LoadHtml(inputHtmlString);
// Parse HTML content for links
var links = htmlContent.DocumentNode.SelectNodes("//a");
foreach (var link in links)
{
link.SetAttributeValue("target", target);
}
return htmlContent.DocumentNode.OuterHtml;
}
并用它来清理我的链接:
// Enforce targets for links as "_blank" to open in new window
asset.Description = asset.Description.SetHtmlLinkTargetAttribute("_blank");
https://stackoverflow.com/questions/2807124
复制相似问题