[英]Remove the extension of filename and convert camelCase to snake case using regex vscode snippets?
I need to create many files on same structure.我需要在同一结构上创建许多文件。 The modules exported and filename have some relation.
导出的模块和文件名有一些关系。 I have to convert.
我必须转换。 Example input and outputs.
示例输入和输出。
startNewGame.ts => start-new-game
gameOver.ts => game-over
ALongNameForAFile.ts=> a-long-name-for-file
short.ts => short
My current regex is我目前的正则表达式是
${TM_FILENAME/([A-Z])/-${1:/downcase}/g}
For now I am only able to remove change capital letter so small and add -
.现在我只能删除这么小的更改大写字母并添加
-
。 There are two problems有两个问题
.ts
.ts
-
in the start.-
在开始。 Note: I am using this in vscode snippets注意:我在 vscode 片段中使用它
You were close on removing the file name extension: use TM_FILENAME_BASE
instead.您即将删除文件扩展名:改用
TM_FILENAME_BASE
。 See vscode snippet variables .请参阅vscode 片段变量。
"filename change": {
"prefix": "_co",
"body": [
"${TM_FILENAME_BASE/(^[A-Z])|([A-Z])/${2:+-}${2:/downcase}${1:/downcase}/g}",
],
"description": ""
},
Since the leading -
only happens when there is a capital letter at the start, I found it easiest to handle that case separately.由于前导
-
仅在开头有大写字母时发生,我发现单独处理这种情况最容易。 So the regex is now:所以正则表达式现在是:
(^[AZ])|([AZ])
// the order is important. (^[AZ])|([AZ])
// 顺序很重要。
${2:+-}
is a conditional, add the -
only if there is a capture group 2. ${2:+-}
是一个条件,只有在有捕获组 2 时才添加-
。
You may use this snippet:您可以使用此代码段:
const arr = ['startNewGame.ts', 'gameOver.ts', 'ALongNameForAFile.ts', 'short.ts']; arr.forEach(s => { console.log( s.replace(/(??^)(,=[AZ])/g. '-').replace(/\,\w+$/. '');toLowerCase() ); });
Here are steps to solve this problem:以下是解决此问题的步骤:
.replace(/(??^)(,=[AZ])/g, '-')
: Insert -
before uppercase letter .replace(/(??^)(,=[AZ])/g, '-')
: 在大写字母之前插入-
.replace(/\.\w+$/, '')
: Remove extension part .replace(/\.\w+$/, '')
: 移除扩展部分.toLowerCase()
: Lowercase resulting string .toLowerCase()
:小写结果字符串
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.