2017-08-05 22 views
1

我有一個字符串(URL):jQuery的正則表達式替換這樣的回報替換單詞的

https://8.random.url.com/g/DFGTER5675/test1/undefined/codec/ 

這裏是我的正則表達式:

/https\:\/\/(?:.*)\/g\/(?:.*)\/(?:.*)\/(.*)\/codec\/(?:.*)/gi 

而且我的代碼:

var string = "https://8.random.url.com/g/DFGTER5675/test1/undefined/codec/"; 
var myRegexp = /https\:\/\/(?:.*)\/g\/(?:.*)\/(?:.*)\/(.*)\/codec\/(?:.*)/gi 
var match = string.replace(myRegexp, "OMEGA3"); 

當我做console.log(match)它只返回「OMEGA3」。我想要的只是我的字符串「undefined」替換爲「OMEGA3」。我究竟做錯了什麼?謝謝。

回答

0

您可以使用此正則表達式與捕獲組和反向引用:

url = url.replace(/(https?:\/\/[^\/]*\/g\/[^\/]*\/[^\/]*\/).*(\/codec\/)/gi, '$1OMEGA3$2'); 

RegEx Demo

+1

完美地工作!謝謝 – user3546553

0

爲什麼不使用/undefined/gi

var string = "https://8.random.url.com/g/DFGTER5675/test1/undefined/codec/"; 
 
var myRegexp = /(https\:\/\/.*?\/.*?\/.*?\/.*?\/).*?(\/.*?\/)/gi 
 
var match = string.replace(myRegexp, "$1OMEGA3$2"); 
 
console.log(match)

+0

您好,感謝您的快速幫助,因爲不確定的可以是任何其他字 – user3546553

+0

我看,更新了我的答案。 – ewwink

0

你必須使用捕獲組的倒退。你應該捕捉你想要保留的模式部分,而不是你想要替換的部分。然後使用$1,$2等將其複製到替換。您也有幾個根本不需要的非捕獲組。

var myRegexp = /(https:\/\/.*\/g\/.*\/).*(\/codec\/)/gi 
var match = string.replace(myRegexp, "$1OMEGA3$2");