如何使用javascript更改html站点的所有URL,以便它们可在子域上工作

时间:2018-08-26 03:58:40

标签: javascript url subdomain

我想知道如何使用javascript更改html站点的所有URL,以便它们在子域上作为备份工作。例如,如果某个网站具有指向http://example.comhttp://example.com/archiveshttp://example.com/about等网址的大量内部链接,那么我该如何将所有这些更改为类似于{{3 }}。任何帮助,将不胜感激。谢谢

2 个答案:

答案 0 :(得分:0)

如果我没有误解您的要求,那么这可能是一种解决方案。参见Element.getElementsByTagName()

function replaceSubdomain(url, subdomain) {
  return url.replace(/^(https?:\/\/)(www\.)?([^.])*/, `$1$2${subdomain}`);
}

let allLinks = document.getElementsByTagName('a');
for (var i = 0; i < allLinks.length; i++) {
  //console.log(allLinks[i].href); 
  allLinks[i].href = replaceSubdomain(allLinks[i].href, 'backup.example');
}
<!DOCTYPE HTML>
<html>

<head>
  <title>Funny Quote Gen</title>

</head>

<body>

  I'm wondering how can I use javascript to change all of the urls of an html site so that they work on a subdomain as a backup. For instance, if a site has a lot of internal links to urls like
  <a href="http://example.com">example</a>,
  <a href="http://example.com/archives">archive</a>,
  <a href="http://example.com/about">about</a>, etc., how could I change all of those to read something like http://backup.example.com. Any help with this would be appreciated. Thanks
</body>

</html>

OR (使用类名方法)-只需在要用<a>等子域替换的<a class="replace_to_subdomain" href="http://example.com/contact">contact</a>上添加一个类名。参见Document.getElementsByClassName()

function replaceSubdomain(url, subdomain) {
  return url.replace(/^(https?:\/\/)(www\.)?([^.])*/, `$1$2${subdomain}`);
}

let allLinks = document.getElementsByClassName('replace_to_subdomain');
for (var i = 0; i < allLinks.length; i++) {
  //console.log(allLinks[i].href);
  allLinks[i].href = replaceSubdomain(allLinks[i].href, 'backup.example');
}
<!DOCTYPE HTML>
<html>

<head>
  <title>Funny Quote Gen</title>

</head>

<body>

  I'm wondering how can I use javascript to change all of the urls of an html site so that they work on a subdomain as a backup. For instance, if a site has a lot of internal links to urls like
  <a href="http://example.com">example</a>,
  <a class="replace_to_subdomain" href="http://example.com/archives">archive</a>,
  <a href="http://example.com/about">about</a> or
  <a class="replace_to_subdomain" href="http://example.com/contact">contact</a> , etc., how could I change all of those to read something like http://backup.example.com. Any help with this would be appreciated. Thanks
</body>

</html>

答案 1 :(得分:0)

您可以为此使用class。例如,看下面的代码。

elements = document.getElementsByClassName('wantToChange');
for (var i = 0; i < elements.length; i++) {
    elements[i].href = "http://subdomain.com";
}
<a href="http://link.com" class="wantToChange">Link 1</a>
<a href="http://link22.com" class="wantToChange">Link 2</a>
<a href="http://link.com" class="wantToChange">Link 3</a>