2017-08-05 25 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");