Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Regex to remove relative path from the url

Another regex pattern question.
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. You get the idea.
All I care about is the actual absolute path which means:
output: hello-world

If anyone can give me a Regex or any functions (preferably in JS), You would save me a ton.
Thanks in advanced.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading