简体   繁体   English

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

[英]javascript regex- replace all instances with one

I want to replace all the words XXX/XXX/XXX/ ... with one XXX/ 我想将所有XXX/XXX/XXX/ ...替换为一个XXX/

For example: 例如:

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

should be: 应该:

www.domain.com/XXX/section/XXX

How can i do it with regex instead of: 我该如何使用正则表达式而不是:

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

Thanks 谢谢

You can use regular expression to match all occurrences of /XXX that are repeated 2 or more times in a row: 您可以使用正则表达式来匹配所有连续出现两次或多次重复的/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); 

Solution

 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) 

Explanation 说明

the () will capture the match inside the parenthesis. ()将捕获括号内的匹配项。

the \\1 and $1 will use whats captured inside the first capture group, the /XXX in our case. \\1$1将使用在第一个捕获组(本例中为/XXX中捕获的内容。

the + will ask for 1 or more repeats. +将要求1个或多个重复。

the g flag will cause the regex to be applied on the whole string, even if a match is found earlier. g标志将导致将正则表达式应用于整个字符串,即使之前已找到匹配项也是如此。

the whole regex will look for an /XXX followed by another /XXX 1 or more times, then replacing whats matched with only one "/XXX". 整个正则表达式将查找/XXX然后查找另一个/XXX 1次或更多次,然后仅用一个“ / XXX”替换匹配的内容。

Try this: 尝试这个:

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

Try this 尝试这个

 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) 

Try: 尝试:

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

To capture and output only first occurrence of XXX/* : 仅捕获和输出首次出现的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) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM