1

Hi there all Im trying to make a snippet in sublime. So that it takes the string and places them into location 1, 2, and so on.

For example this is my string:

a, b, c, d, e

I want to run snippet on it so it makes it into:

console.info('a:', a, 'b:', b, 'c:', c, 'd:', d, 'e:', e);

I want it to work for any number of variables, so even for a, b, c it will spit out console.info('a:', a, 'b:', b, 'c:', c)

I tried all kinds of sublime snippet tutorials but couldnt manage it, is this possible?

1 Answer 1

2

Sublime text has snippet substitutions but maybe you are not familiar with it syntax. You can use this example snippet content:

<content><![CDATA[
console.info(${SELECTION/(\w+)[^\w]*/'\1\:', \1, /g}'_END_');
]]></content>

Explanation:

We replace every occurence of

(\w+)[^\w]*

in selection with:

'\1\:', \1, 
  • Inside the regex \w matches a word character (letter, number or undescore). Those are the characters that variable names use.
  • \w+ matches contiguos \w, so it matches a variable name, while [\w]* matches non word characters (spaces, commas, separators...)
  • In the parénthesis we are capturing a group corresponding the variable name, lets call it first group.
  • Then comes the replacemenet. \1 means output the string that was captured in the first group (variable name). So the entire '\1\:', \1, replacement gets replaced for 'variableName:', variableName
  • \g modifier means that this is done globally, for every variable name inside the selection ($SELECTION variable).

This part adds a problem, as a, b, c, d is replaced for 'a:', a, 'b:', b, 'c:', c, 'd:', d, (look at the problematic extra final comma). Thats why I added a final '_END_' token, this is a workarund that maybe you want to replace by an empty string.

Have in mind that we are not making distintion of separators between variable names, so you can use commas, spaces, quotes, etc. as only the variable name will be captured.

So both:

age, name, height, weight
age     name,   height       weight

Are replaced when the text is selected and the snippet is called (key-binding or command palete) with:

console.info('age:', age, 'name:', name, 'height:', height, 'weight:', weight, '_END_');
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.