You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用JavaScript从绝对文件路径中捕获无斜杠的文件名分组

How to Precisely Capture Filename Without Slashes from File Paths

Got it, let's sort out this regex problem for you! The issue with your original regex /\/(.*).js/ is that it uses greedy matching—so it grabs everything from the first / all the way up to .js, which is why you're getting extra path content instead of just the filename.

Here are a few reliable ways to fix this:

1. Use a Negated Character Set (Most Universal Regex Approach)

This regex targets the last segment before .js by matching only characters that aren't slashes, anchored to the end of the string:

\/([^\/]+)\.js$

Let's break it down:

  • [^\/]+: Matches one or more characters that aren't a forward slash (this ensures we only capture the filename part, not any preceding path segments)
  • \.js: Escapes the dot to match the literal .js extension
  • $: Anchors the match to the end of the string, so we don't accidentally match .js somewhere earlier in the path

Testing this on your examples:

  • For /Users/X/Q/Q-doc/src/templates/demos.js, the captured group will be demos
  • For /Users/X/Q/Q-doc/src/templates/demos1.js, the captured group will be demos1

2. Use Lookaround Assertions (Cleaner Zero-Width Match)

If you don't want to rely on capturing groups (or just prefer a more concise pattern), you can use lookaround assertions to isolate the filename:

(?<=\/)[^\/]+(?=\.js$)
  • (?<=\/): Positive lookbehind—ensures the match is preceded by a forward slash
  • (?=\.js$): Positive lookahead—ensures the match is followed by .js at the end of the string
  • The middle [^\/]+ is your target filename, no capturing group needed

3. Non-Regex Alternatives (If You're Using JavaScript/Node.js)

If you're working in JavaScript, sometimes string methods or built-in modules are simpler than regex:

Using String Methods:

const filePath = '/Users/X/Q/Q-doc/src/templates/demos.js';
const filename = filePath.split('/').pop().slice(0, -3);
// Result: "demos"

Using Node.js path Module (Best Practice for File Paths):

const path = require('path');
const filePath = '/Users/X/Q/Q-doc/src/templates/demos1.js';
const filename = path.parse(filePath).name;
// Result: "demos1"

All these methods will reliably capture the exact filename you need without extra path content.

内容的提问来源于stack exchange,提问作者XYZ

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 03:11:16