我需要使用JavaScript来更改mailto:href链接到新的电子邮件域

时间:2018-03-11 21:25:59

标签: javascript html

在工作中,我们有一个非常古老的ASP.Net网站,在我们的页面上显示了要联系的人,有一堆<a>个标签,上面有mailto:个链接,用于不同的电子邮件部门。

由于这个网站是很久以前建立的,我们不想尝试在Visual Studio中打开它并且因为害怕弄乱某些东西而改变它们,因为该网站仍然非常适合它的目的。它是用Visual Studio .NET 2003编写的,我们只是不想冒险。我们甚至没有任何旧版本的VS副本。我们现在所有的东西都是使用Visual Studio 2013及以上编写的。

所以说到这一点,我注意到当我在这个特定页面上创建一个视图源时,链接到一个名为clmenu.js的JavaScript文件或类似的东西。所以我想我只是打开那个JS文件并在顶部添加一些代码来更改到新域的所有链接。所以页面上的所有链接都是这样的

<a href="mailto:whateverdepartment@olddomain.com">whateverdepartment@olddomain.com</a>

我需要更改指向此链接:

<a href="mailto:whateverdepartment@newdomain.com">whateverdepartment@newdomain.com</a> 

是否可以使用JavaScript在所有这些链接上将@ olddomain.com更改为@ newdomain.com?我必须使用普通的旧JavaScript,而不是jQuery;因为jQuery没有在这个网站上使用。

1 个答案:

答案 0 :(得分:0)

可能有更好的方法可以做到这一点,但这可以帮助您解决大多数案例:

document.querySelectorAll('a[href^="mailto:"][href$="olddomain.com"]') // match all links beginning with "mailto" and ending with "olddomain.com"
  .forEach(e => {
    e.href = e.href.split("@")[0] + "@newdomain.com"; // split the string into an array without the @ sign and put it back together 
    e.innerHTML = e.innerHTML.split("@")[0] + "@newdomain.com"; // do the same here
  });
<a href="mailto:somedep@olddomain.com">somedep@olddomain.com</a><br>
<a href="mailto:somedep2@olddomain.com">somedep2@olddomain.com</a><br>
<a href="mailto:anotherdep@anothercompany.com">anotherdep@anothercompany.com</a>