JavaScript正则表达式替换给定URL中的文本

时间:2017-05-26 17:46:04

标签: javascript regex

我正在使用网络工具来推广带有我的会员链接的产品。 我需要修改URL如下。

我的网址可能采用这种格式

https://www.example.com/productid
http://www.example.com/productid&
https://www.example.com/productid
https://example.com/productid
http://example.com/productid

现在我需要编写一个正则表达式来将这些URL转换为这种格式

https://abc.example.com/abc/productid

有人可以帮助使用正则表达式吗?

1 个答案:

答案 0 :(得分:0)

这有用吗?

正则表达式:

https?:\/\/(?:www\.)?example\.com\/productid(?:.*)

替换为:https://abc.example.com/abc/productid

Regex101 Demo

var input = `https://www.example.com/productid
http://www.example.com/productid&
https://www.example.com/productid
https://example.com/productid
http://example.com/productid
httpL//www.stackoverflow.com`

var replaceWith = "https://abc.example.com/abc/productid";
output = input.replace(/https?:\/\/(?:www\.)?example\.com\/productid(?:.*)/g, replaceWith);
console.log(output);