如何用JavaScript从绝对文件路径中捕获无斜杠的文件名分组
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.jsextension$: Anchors the match to the end of the string, so we don't accidentally match.jssomewhere earlier in the path
Testing this on your examples:
- For
/Users/X/Q/Q-doc/src/templates/demos.js, the captured group will bedemos - For
/Users/X/Q/Q-doc/src/templates/demos1.js, the captured group will bedemos1
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.jsat 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

