javascript正则表达式 - 用一个替换所有实例

时间:2017-08-01 06:21:07

标签: javascript regex

我想用XXX/XXX/XXX/

替换所有单词XXX/ ...

例如:

www.domain.com/XXX/XXX/XXX/XXX/XXX/section/XXX/XXX

应该是:

www.domain.com/XXX/section/XXX

我怎么能用正则表达式代替:

str.replace("XXX/XXX","XXX").replace("XXX/XXX","XXX").replace("XXX/XXX","XXX").replace("XXX/XXX","XXX").replace("XXX/XXX","XXX").replace("XXX/XXX","XXX");

由于

6 个答案:

答案 0 :(得分:2)

您可以使用正则表达式来匹配连续重复2次或更多次的/XXX次出现:



var str = "www.domain.com/XXX/XXX/XXX/XXX/XXX/section/XXX/XXX";

var strOut = str.replace(/(\/XXX){2,}/g, '$1');

console.log(strOut);




答案 1 :(得分:2)

解决方案

const input = "www.domain.com/XXX/XXX/XXX/XXX/XXX/section/XXX/XXX";

const expectedOutput = "www.domain.com/XXX/section/XXX"
const actualOutput = input.replace(/(\/XXX)\1+/g, "$1")

console.log("output", actualOutput)

解释

()将捕获括号内的匹配。

\1$1将使用在第一个捕获组中捕获的内容,在我们的情况下为/XXX

+会要求重复1次或更多次。

g标志将导致正则表达式应用于整个字符串,即使之前找到了匹配项。

整个正则表达式会查找/XXX后跟另一个/XXX 1次或更多次,然后替换仅与一个“/ XXX”匹配的内容。

答案 2 :(得分:1)

试试这个:

var str = "www.domain.com/XXX/XXX/XXX/XXX/XXX/section/XXX/XXX";
str = str.replace(/(XXX\/*)+/g, "XXX/");
console.log(str);

答案 3 :(得分:1)

试试这个

var url="www.domain.com/XXX/XXX/XXX/XXX/XXX/section/XXX/XXX";
var regexer=/(XXX\/*)+/g;
url = url.replace(regexer, "XXX/");
console.log(url)

答案 4 :(得分:1)

尝试:

function processUrl(url) {
  return url.replace(/www.domain.com(\/[^/]*)*\/section(\/[^/]*)*/g, "www.domain.com$1/section$2");
}
console.log(processUrl("www.domain.com/XXX/XXX/XXX/XXX/XXX/section/XXX/XXX"));
console.log(processUrl("www.domain.com/XXX/XXX/XXX/XXX/XXX/section/YYY/YYY"));
console.log(processUrl("www.domain.com/XXX/XXX/XXX/XXX/section/ZZZ/ZZZ/ZZZ"));

答案 5 :(得分:1)

仅捕获并输出第一次出现的XXX/*

var url="www.domain.com/XXX/XXX/XXX/XXX/XXX/section/XXX/XXX";
var re=/(XXX\/*)+/g;
url = url.replace(re, "$1");
console.log(url)