转义反斜杠 JS 时的意外行为

Unexpected Behavior When Escaping Backslashes JS

所以我正在制作一个简单的函数来分隔文件名和目录路径。我相信节点的 Path 模块有更简单的方法,但我想我会为这个项目自己做。

所以问题是当我在字符串中写反斜杠字符时,我在字符串中将它们转义为 "directory\AnothaDirectory"。它运行了,但是为了转义而使用的双“\”和“\\”在解析后仍然保留在字符串中。例如:"C:\Documents\Newsletters"。

我都尝试过使用单个反斜杠,这会像预期的那样抛出编译器错误。但我也尝试过使用正斜杠。反斜杠没有被转义的原因可能是什么?

function splitFileNameFromPath(path,slashType){

    let pathArray = path.split(slashType),
        fileName = pathArray[pathArray.length - 1],
        elsIndexes = pathArray.length - 1,
        pathSegs = pathArray.slice(0, elsIndexes);              

    let dirPath = pathSegs.join(slashType);
    //adds an extra slash after drive name and colon e.g."C:\"   
    dirPath = dirPath.replace( new RegExp("/\/","ug"), "\" )
    //removes illegal last slash
    let pathSeg = pathSegs.slice(0,-1)
    return [dirPath, fileName]
}

let res = splitFileNameFromPath("C:\\Documents\Newsletters\Summer2018.pdf","\");
console.log(res)

这段代码中有些地方我不明白。

  1. "C:\\Documents\Newsletters\Summer2018.pdf"(即 "C:\Documents\Newsletters\Summer2018.pdf")似乎不是有效的 Windows 路径,因为通常使用的驱动器号后没有双斜杠(它是不像 URL 'https://...').

  2. new RegExp("/\/","ug") 等于 /\/\//gu 并且不匹配任何内容。

  3. 根本没有使用let pathSeg = pathSegs.slice(0,-1)的结果

在我看来这段代码足以完成任务:

'use strict';

function splitFileNameFromPath(path, slashType) {
  const pathArray = path.split(slashType),
        fileName = pathArray.pop(),
        dirPath = pathArray.join(slashType);

  return [dirPath, fileName];
}

const path = "C:\Documents\Newsletters\Summer2018.pdf";
const slash = "\";

const res = splitFileNameFromPath(path, slash);

console.log(res);
console.log(path === res.join(slash));