Get lines of Strings into an "array"

Viewed 2222

I have often lines of strings in VSCode, but would need an array for PowerShell or SQL.

I have in VSCode

line1
line2
line3

I would need somthing like that in Vscode

('line1','line2','line3')

Resulting in

Select * from Table where Column in ('line1','line2','line3')

or

$a = 'line1','line2','line3'

Is there an function / extension for this?

2 Answers

array build demoYou could make a snippet that'll do this easily. Add a keybinding to trigger that snippet in keybindings.json:

{
  "key": "alt+b",                             // or whatever keybinding you want
  "command": "editor.action.insertSnippet",
  "args": {
    "snippet": "(${TM_SELECTED_TEXT/\\s*(.+)(\\s)?/'$1'${2:+,}/g})"
  }
}

${TM_SELECTED_TEXT/\\s*(.+)(\\s)?/'$1'${2:+,}/g} get the selected text. The regex will get the text of each line in capture group 1, and any newline character in capture group 2.

Then 'group 1' is added followed by a , only if there is a group 2. Because of the g regex flag this will happen for all lines.


If you want empty lines to be represented as an empty strings in your output, use

  "snippet": "(${TM_SELECTED_TEXT/((.+)(\\r\\n))|(.+)|(\\r\\n)/'$2$4'${3:+,}${5:+,}/g})"

Demo of this:

empty lines demo


If you want this output of the snippet:

Select * from Table where Column in ('line1','line2','line3')

then use:

"snippet": "Select * from Table where Column in (${TM_SELECTED_TEXT/\\s*(.+)(\\s)?/'$1'${2:+,}/g})"

You can do that using regex replace:

  • Select lines of code you wish to join
  • ctrl+h, change mode to Regular Expressions
  • in Find type \n
  • in Replace type '),('
  • Replace All

There's no need to add \r in Find or escape parenthesis in Replace.

screen

Related