簡體   English   中英

刪除文件名的擴展名並使用正則表達式 vscode 片段將 camelCase 轉換為蛇形大小寫?

[英]Remove the extension of filename and convert camelCase to snake case using regex vscode snippets?

我需要在同一結構上創建許多文件。 導出的模塊和文件名有一些關系。 我必須轉換。 示例輸入和輸出。

startNewGame.ts => start-new-game
gameOver.ts => game-over
ALongNameForAFile.ts=> a-long-name-for-file
short.ts => short

我目前的正則表達式是

${TM_FILENAME/([A-Z])/-${1:/downcase}/g}

現在我只能刪除這么小的更改大寫字母並添加- 有兩個問題

  • 我無法刪除.ts
  • 有額外的-在開始。

注意:我在 vscode 片段中使用它

您即將刪除文件擴展名:改用TM_FILENAME_BASE 請參閱vscode 片段變量

"filename change": {
  "prefix": "_co",
  "body": [
    "${TM_FILENAME_BASE/(^[A-Z])|([A-Z])/${2:+-}${2:/downcase}${1:/downcase}/g}",
  ],
  "description": ""
},

由於前導-僅在開頭有大寫字母時發生,我發現單獨處理這種情況最容易。 所以正則表達式現在是:

(^[AZ])|([AZ]) // 順序很重要。

${2:+-}是一個條件,只有在有捕獲組 2 時才添加-

您可以使用此代碼段:

 const arr = ['startNewGame.ts', 'gameOver.ts', 'ALongNameForAFile.ts', 'short.ts']; arr.forEach(s => { console.log( s.replace(/(??^)(,=[AZ])/g. '-').replace(/\,\w+$/. '');toLowerCase() ); });

以下是解決此問題的步驟:

  • .replace(/(??^)(,=[AZ])/g, '-') : 在大寫字母之前插入-
  • .replace(/\.\w+$/, '') : 移除擴展部分
  • .toLowerCase() :小寫結果字符串

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM