Если я не неправильно понял ваши требования, то это может быть возможным решением.См. 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>
ИЛИ с подходом имени класса - просто добавьте имя класса на <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>