我正在嘗試從字串中獲取路徑的第一段。
當前行為:
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。
uj5u.com熱心網友回復:
你可以做這樣的事情
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));
uj5u.com熱心網友回復:
使用帶有虛假基本 URL 的 URL 并訪問該屬性pathname。
const BASE = "https://example.com";
const paths = [
'', // empty
'/', // root
'/tasks/123456789', // sub-directory
'/tasks', // single
'/tasks?name=Doe', // query
'/tasks#fragment', // hash / fragment
];
paths.forEach(path => {
const url = new URL(path, BASE);
// pathname ALWAYS starts with a `/` so grab the first index
const [ _, firstSegment ] = url.pathname.split("/");
console.log(`${path} -> ${firstSegment}`);
});
uj5u.com熱心網友回復:
您在 .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”字串也拆分為“?”
uj5u.com熱心網友回復:
如果您從window物件中獲取字串,則可以從屬性中獲取路徑名window.location
const pathParts = window.location.pathname.split('/');
否則你可以構造一個URL物件
const myUrl = new URL('https://www.example.com/get/the/pathname?param=1¶m=2');
const pathParts = myUrl.pathname.split('/');
如果您正在處理路徑字串(不是有效的 url),我會建議類似
const myStr = '/get/the/pathname?paramA=1¶mB=2';
const parts = myStr.split('?')[0].split('/');
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/465362.html
標籤:javascript 反应 细绳
上一篇:在SpringAuthorizationServer(0.2.3 )中支持并發全堆疊MVC(session)認證以及無狀態JWT認證
