2017-05-26 57 views
-1

我正在使用我的會員鏈接來推廣產品的網絡工具。 我需要修改一個URL如下。JavaScript正則表達式替換給定URL中的文本

我的URL可能在這種格式

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

現在我需要寫一個正則表達式將這些網址轉換成這種格式

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

有人可以用正則表達式來做到這一點幫助?

+0

爲什麼不直接用'.COM/ABC /替換'.COM /' ''和'http:'用'https:'用'.replace()'? https://www.w3schools.com/jsref/jsref_replace.asp –

回答

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);

+0

不適用於此案例:https://regex101.com/r/vCWQ8U/4 – Uday

+0

您應該清楚您的要求。將所有條件和示例添加到問題中。如何:https://regex101.com/r/vCWQ8U/5? – degant