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

Best way to get the pathname from string

I am trying to get the first segment of the path from a string.

Current Behaviour:

const pathOne = '/tasks/123456789';
const pathTwo = '/tasks';
const pathThree = '/tasks?name=Doe';

const resultOne = pathOne.split('/')[1];
const resultTwo = pathTwo.split('/')[1];
const resultThree = pathThree.split('/')[1];

console.log(resultOne, resultTwo, resultThree);

As you see in the above code, I tried split the string and get second element from the array which has the first segment of the path.

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

But unfortunately in the last one, I get query params along with it, which I intend to remove it and get only tasks for all three strings.

Kindly please help me with efficient way of achieving the result that gives only the first segment of the path and ignore query params.

Note:
Please don’t consider it as url and it is just a normal string with pathname and I am intend to get only the first segment of it tasks .

>Solution :

You can do somethong like this

const pathOne = '/tasks/123456789';
const pathTwo = '/tasks';
const pathThree = '/tasks?name=Doe';

const getFile = fullPath => {
const [path, query] = fullPath.split('?')
 return path.split('/')[1]
}



console.log(getFile(pathOne));
console.log(getFile(pathTwo));
console.log(getFile(pathThree));
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