首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >用javascript或jquery更改链接的域部分

用javascript或jquery更改链接的域部分
EN

Stack Overflow用户
提问于 2011-09-16 19:32:29
回答 4查看 9.6K关注 0票数 5

对不起,我原来的问题不清楚,希望通过重新措辞,我可以更好地解释我想做什么。

因此,我需要一种使用JavaScript (或jQuery)来执行以下操作的方法:

确定当前页面的域为accessed

  • identify --使用域www.domain1.com并替换为www.domain2.com

的页面上的所有链接

也就是说,如果用户正在访问www.domain2.com/index,那么:

代码语言:javascript
复制
<a href="www.domain1.com/contentpages/page.html">Test 1</a>

应该在加载时动态重写到

代码语言:javascript
复制
<a href="www.domain2.com/contentpages/page.html">Test 1</a>

可以在href标记中只重写url的一部分吗?

EN

Stack Overflow用户

发布于 2021-01-17 14:51:19

使用REGEX替换urls域

本例将使用my-domain.com将所有urls替换为my-other-domain (都是变量)。

可以通过在原始字符串模板中组合字符串值和其他regex表达式来执行动态正则表达式。使用String.raw将防止javascript转义字符串值中的任何字符。

代码语言: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代码.

票数 0
EN
查看全部 4 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7449480

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档