从字符串中获取路径名的最佳方法

Best way to get the pathname from string

我正在尝试从字符串中获取路径的第一段。

当前行为:

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

正如您在上面的代码中看到的,我尝试拆分字符串并从具有路径第一段的数组中获取第二个元素。

但不幸的是,在最后一个中,我得到了查询参数,我打算将其删除并只获得 所有三个 字符串的 tasks

请用高效的方式帮助我实现只给出路径的第一段和忽略查询参数的结果。

注: 请不要将其视为 url 它只是一个带有路径名的普通字符串,我打算只获取它的第一段 tasks .

您在 .split() -> [1] 之后有索引键。当你有键索引时,你告诉我“给我第一个从字符串中分离出来的单词” 如果你删除它,你可以得到每个字符串用“/”分隔。试试 :)

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

编辑:如果您不想查询参数,则必须将“pathThree”字符串也拆分为“?”

如果您从 window 对象获取字符串,您可以从 window.location 属性

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

否则你可以构造一个URL对象

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

如果您正在处理路径字符串(不是有效的 url),我建议您使用

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

你可以这样做

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

enter code hereconst 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);