jQuery正则表达式替换返回替换单词

时间:2017-08-05 07:05:24

标签: javascript jquery regex

我有一个像这样的字符串(url):

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"。我究竟做错了什么?感谢。

3 个答案:

答案 0 :(得分: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)

答案 1 :(得分:0)

您可以向后使用捕获组。您应该捕获要保留的模式部分,而不是要替换的部分。然后使用$1$2等将这些内容复制到替换。

您还有几个根本不需要的非捕获组。

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

答案 2 :(得分:0)

您可以将此正则表达式用于捕获组和反向引用:

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

RegEx Demo

相关问题