[英]Download a portion of a website on a different domain to a variable in JavaScript without jQuery?
[英]change domain portion of links with javascript or jquery
抱歉,我最初的問題不清楚,希望通過改寫我可以更好地解釋我想要做什么。
因此,我需要一種使用 JavaScript(或 jQuery)來執行以下操作的方法:
即如果用戶正在訪問 www.domain2.com/index 那么:
<a href="www.domain1.com/contentpages/page.html">Test 1</a>
應該在加載時動態重寫
<a href="www.domain2.com/contentpages/page.html">Test 1</a>
甚至可以只重寫href
標簽中的一部分 url 嗎?
您的代碼將遍歷頁面上的所有鏈接。 這是一個僅迭代需要替換的 URL 的版本。
var linkRewriter = function(a, b) {
$('a[href*="' + a + '"]').each(function() {
$(this).attr('href', $(this).attr('href').replace(a, b));
});
};
linkRewriter('originalDomain.com', 'rewrittenDomain.com');
我想出了如何使這項工作。
<script type="text/javascript">
// link rewriter
$(document).ready (
function link_rewriter(){
var hostadd = location.host;
var vendor = '999.99.999.9';
var localaccess = 'somesite1.';
if (hostadd == vendor) {
$("a").each(function(){
var o = $(this);
var href = o.attr('href');
var newhref;
newhref = href.replace(/somesite1/i, "999.99.999.99");
o.attr('href',newhref);
});
}
}
);
</script>
此示例將使用my-domain.com
所有 url 替換為my-other-domain
(兩者都是變量)。
您可以通過在原始字符串模板中組合字符串值和其他正則表達式來執行動態正則表達式。 使用String.raw
將防止 javascript 轉義字符串值中的任何字符。
// Strings with some data
const domainStr = 'my-domain.com'
const newDomain = 'my-other-domain.com'
// Make sure your string is regex friendly
// This will replace dots for '\'.
const regexUrl = /\./gm;
const substr = `\\\.`;
const domain = domainStr.replace(regexUrl, substr);
// domain is a regex friendly string: 'my-domain\.com'
console.log('Regex expresion for domain', domain)
// HERE!!! You can 'assemble a complex regex using string pieces.
const re = new RegExp( String.raw `([\'|\"]https:\/\/)(${domain})(\S+[\'|\"])`, 'gm');
// now I'll use the regex expression groups to replace the domain
const domainSubst = `$1${newDomain}$3`;
// const page contains all the html text
const result = page.replace(re, domainSubst);
注意:不要忘記使用 regex101.com 來創建、測試和導出 REGEX 代碼。
您需要使用 Java 或服務器端的東西來獲取 IP 地址。 看到這個:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.