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