Home > Software design >  Best way to get the pathname from string
Best way to get the pathname from string

Time:04-27

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 .

CodePudding user response:

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

CodePudding user response:

You have index key after .split() -> [1]. When you have key index, you told "Give me first separated word from string" If you remove it, you can get every string separated by "/". Try :)

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

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

console.log(resultOne, resultTwo, resultThree);

EDIT: IF you don't wanna query parameters, you must split "pathThree" string also by "?"

CodePudding user response:

If you're getting the string from the window object you can obtain the pathname from the window.location property

const pathParts = window.location.pathname.split('/');

Otherwise you can construct an URL object

const myUrl = new URL('https://www.example.com/get/the/pathname?param=1&param=2');
const pathParts = myUrl.pathname.split('/');

If you're working on a path string (not a valid url) I'd suggest something like

const myStr = '/get/the/pathname?paramA=1&paramB=2';
const parts = myStr.split('?')[0].split('/');

  • Related