【问题标题】:How to extract part of string an array of strings in Node.js?如何在Node.js中提取部分字符串和字符串数组?
【发布时间】:2020-02-05 07:32:30
【问题描述】:

我正在尝试为数组中的每个元素提取字符串的一部分。

我已设法获取所有以 .pdf 结尾的文件,但我不知道如何进行提取部分。

我会假设我需要使用正则表达式来完成这项工作,但是,我不确定从哪里开始。

给定第一个元素./pdf/main/test1.pdf,我想返回/test1.pdf

按照我下面的代码:

    glob('./pdf/main/*.pdf', {}, (err, files) => {
      console.log(files) // ['./pdf/main/test1.pdf','./pdf/main/test2.pdf' ]
      files.map(f => { 
        // Here I want to extract and return the following output:
        // /test1.pdf
        // /test2.pdf
      })
    })

【问题讨论】:

    标签: javascript node.js


    【解决方案1】:

    字符串拆分和使用path.basename可能很容易理解。

    如果您想知道如何使用正则表达式提取文件名,您可以尝试以下代码

    glob('./pdf/main/*.pdf', {}, (err, files) => {
       files.map(f => f.match(/.*(?<filename>\/.+?\.pdf)/).groups.filename)
    }
    

    【讨论】:

      【解决方案2】:

      使用 split 并检索最后一个值应该可以做到这一点

      glob('./pdf/main/*.pdf', {}, (err, files) => {
        console.log(files) // ['./pdf/main/test1.pdf','./pdf/main/test2.pdf' ]
        files.map(f => { 
          let split = f.split('/'); // ['.', 'pdf', 'main', 'test1.pdf']
          return `/${split[split.length - 1]}`; // /test1.pdf
        })
      })
      

      此外,由于您已标记 node.js,并假设这与文件路径有关,您可以使用 path 模块的 basename 函数来执行此操作,请参见此处

      nodejs get file name from absolute path?

      glob('./pdf/main/*.pdf', {}, (err, files) => {
        console.log(files) // ['./pdf/main/test1.pdf','./pdf/main/test2.pdf' ]
        files.map(f => `/${path.basename(f)}`); // ['/test1.pdf',  '/test2.pdf']
      })
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-02-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多