对不起,我原来的问题不清楚,希望通过重新措辞,我可以更好地解释我想做什么。
因此,我需要一种使用JavaScript (或jQuery)来执行以下操作的方法:
确定当前页面的域为accessed
的页面上的所有链接
也就是说,如果用户正在访问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的一部分吗?
发布于 2021-01-17 14:51:19
使用REGEX替换urls域
本例将使用my-domain.com将所有urls替换为my-other-domain (都是变量)。
可以通过在原始字符串模板中组合字符串值和其他regex表达式来执行动态正则表达式。使用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代码.
https://stackoverflow.com/questions/7449480
复制相似问题