0

I want to replace all the words XXX/XXX/XXX/... with one 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

6 Answers 6

2

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.

the + will ask for 1 or more repeats.

the g flag will cause the regex to be applied on the whole string, even if a match is found earlier.

the whole regex will look for an /XXX followed by another /XXX 1 or more times, then replacing whats matched with only one "/XXX".

Sign up to request clarification or add additional context in comments.

Comments

2

You can use regular expression to match all occurrences of /XXX that are repeated 2 or more times in a row:

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

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

console.log(strOut);

Comments

1

Try this:

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

Comments

1

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)

Comments

1

To capture and output only first occurrence of 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)

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.