Skip to content Skip to sidebar Skip to footer

Replace Mailto-links

I've got this example string: var content = 'Lorem ipsum dolor sit amet info@xxx.com ipsum dolor

Solution 1:

Solution 2:

Convert the content to XML and then simply search for the a tags that contain an href that starts with mailto:

You'll need this using to use XPath: using System.Xml.XPath;

var content = "Lorem ipsum dolor sit amet <a href=\"mailto:info@xxx.com\">info@xxx.com</a> ipsum dolor <a href=\"mailto:info@yyy.eu\">info@yyy.eu</a> adipiscing elit.";

XElement x = XElement.Parse(string.Format("<root>{0}</root>", content));
var hrefs = x.XPathSelectElements("a[starts-with(@href, 'mailto:')]");
foreach (XElement href in hrefs)
{
    href.Attribute("href").Value = "#";
    href.Add(new XAttribute("title", "protected"));

    string email = href.Value;
    int at = email.IndexOf('@');
    if(at > 0)
    {
        string username = email.Substring(0, at);
        string domain = email.Substring(at);
        if (username.Length > 2)
            href.Value = string.Format("{0}..{1}", 
                username.Substring(0, 2), domain);
    }
}
string result = string.Concat(x.Nodes().ToArray());

Post a Comment for "Replace Mailto-links"