Wrap in quotes all fields of an object with VIM substitute command

Viewed 54

I want to convert

{
  foo:"bar",
  hello:"world",
}

into

{
  "foo":"bar",
  "hello":"world",
}

I'm thinking about a substitute commande like this

s/(.*):/"<the_thing_captured_on_the_left>"/g

But how do I access the content before : to wrap it in quotes ?

1 Answers

Use this

:%s/\w\+:\@=/"&"/

where \@= applies to the token before it (in this case :) and means "if : matches, match with zero width just before it (:help /zero-width).

And all the rest should be clear given the background you demonstrate.

Equivalently, you can do

:%s/\w\+\ze:/"&"/

where \ze means "match the stuff after this, but don't consume it".

Related