3 回答

TA貢獻1853條經驗 獲得超6個贊
const str = String.raw`Desktop\Folder\file.txt`;
const parts = str.split(`\\`);
const file = parts.pop();
const path = parts.slice(0).join(`\\`);
console.log(file)
console.log(path)
注意:我用來String.raw
保留正斜杠,你可能不需要這個

TA貢獻1820條經驗 獲得超9個贊
您可以使用 stringsubstring來獲取斜杠的最后一個索引(因為這是一個很好的指示器filename.type。
這 \\ 只是為了逃避 \
例子:
function splitPath(path) {
return {
path: path,
file: path.substring(path.lastIndexOf('\\') + 1, path.length)
};
}
const path = 'C:\\Users\\alexr\\Desktop\\filename.type';
console.log(splitPath(path));

TA貢獻1820條經驗 獲得超2個贊
您需要像這樣分割文件路徑,
JSON.stringify(str).split("\\");
這里不需要改變你的輸入,如果你想分割帶有反斜杠的字符串,那么使用,
.split("\\")
片段如下,
const str = "Desktop\filename.type";
const res = JSON.stringify(str).split("\\");
const result = JSON.parse(res).split(',');
const path = result[0];
const file = result[1];
console.log(path);
console.log(file);
編輯:
好吧,這就是我使用 的原因JSON.stringify(),因為字符串有反斜杠,它會忽略后面的下一個字符backslash,因此要獲取實際的字符串,這里我使用了,JSON.stringify..您可以在下面的控制臺中找到兩者之間的區別。
const str = "Desktop\filename.type";
console.log(str);
console.log(JSON.stringify(str))
console.log(JSON.stringify(str));
當你分割實際的字符串時,
.split("\\"),
結果將是單個字符串數組..
const str = "Desktop\filename.type";
console.log(str.split("\\"));
- 3 回答
- 0 關注
- 217 瀏覽
添加回答
舉報