Home > Mobile >  Regex to remove relative path from the url
Regex to remove relative path from the url

Time:10-22

I have a use case, where any format of relative can happen. Like:

const URL1 = "./hello-world"
const URL2 = "../hello-world"
const URL3 = "../../hello-world"
const URL4 = "../../../hello-world"
const URL5 = "../../../../hello-world"

So on and so forth. All I care about is the actual absolute path which means:

output: hello-world

Which Regex or functions (preferably in JS) could I use to achieve this?

CodePudding user response:

const input = "../../../../hello-world";
const output = input.replace(/\. \//g, '');
console.log(output); // hello-world

What it does is to find '.' chain which ends with the '/'. It will match every chain of dots which ends with slash.

  • Related