我正在尝试分割任何任意文件路径,例如:
“c:\\directory\\another_directory\\filename.ext”
(Windows 操作系统)
或
“c:/directory/another_directory/filename.ext”
(UNIX)
到一个数组中,用“\\”或“/”分隔(取决于读取文件路径字符串的操作系统)。
所需的输出是一个数组,例如:
['c:', 'directory', 'another_directory', 'filename.txt']
我可以在 split 方法中使用什么正则表达式,例如:
str.split(new RegExp(/(\\|/)/i))
(无效的正则表达式)
预先感谢您的帮助。
最佳答案
使用.match
,匹配既不是斜杠也不是反斜杠的字符:
const doSplit = str => str.match(/[^/\\]+/g);
console.log(doSplit(String.raw`c:\\directory\\another_directory\\filename.ext`));
console.log(doSplit("c:/directory/another_directory/filename.ext"));
关于javascript - 如何在 Javascript 中使用 "\\"或 "/"作为分隔符(即在单个正则表达式中)将字符串拆分为数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58359697/