Home > Net >  How can I replace all duplicated paths of a url with a JS Regex
How can I replace all duplicated paths of a url with a JS Regex

Time:10-12

For the following URL: https://www.google.es/test/test/hello/world

I want to replace all the occurrences of "/test/", and its important that it "test" starts with and ends with a "/".

I tried with:

let url = "https://www.google.es/test/test/hello/world"
url.replace(/\/test\//g, "/");

But it returns: 'https://www.google.es/test/hello/world'

It doesn't replace the second "/test/"

Any clues on how I could do this with a regex?

I basically want to replace the content that lives inside the dashes, but not the dashes themselves.

CodePudding user response:

You can do this with a regular expression, but it sounds like your intent is to replace only individual parts of the pathname component of a URL.

A URL has other components (such as the fragment identifier) which could contain the pattern that you describe, and handling that distinction with a regular expression is more challenging.

The URL class is designed to help solve problems just like this, and you can replace just the path parts using a functional technique like this:

function replacePathParts (url, targetStr, replaceStr = '') {
  url = new URL(url);
  const updatedPathname = url.pathname
    .split('/')
    .map(str => str === targetStr ? replaceStr : str)
    .filter(Boolean)
    .join('/');
  url.pathname = updatedPathname;
  return url.href;
}

const inputUrl = 'https://www.google.es/test/test/hello/world';

const result1 = replacePathParts(inputUrl, 'test');
console.log(result1); // "https://www.google.es/hello/world"

const result2 = replacePathParts(inputUrl, 'test', 'message');
console.log(result2); // "https://www.google.es/message/message/hello/world"

CodePudding user response:

Something like this would work:

/(\/[^\/] )(?:\1) \//g
  • ( - open capture group #1
    • \/ - find a literal slash
    • [^\/] - capture at least one non-slash char
  • ) - close capture group #1
  • (?:\1) - repeat capture group #1 one or more times
  • \/ - ensure a closing slash
  • /g - global modifier

https://regex101.com/r/NgJA3X/1

var regex = /(\/[^\/] )(?:\1) \//g;

var str = `https://www.google.es/test/test/hello/world
https://www.google.es/test/test/test/test/hello/world
https://www.google.es/test/test/hello/test/hello/hello/world
https://www.google.es/test/hello/world/world
https://www.google.es/test/hello/helloworld/world`;
var subst = ``;

// The substituted value will be contained in the result variable
var result = str.replace(regex, subst);

console.log(result);

  • Related