0

So I created a large number of javascript objects with literal syntax and I forgot to use quotes for the keys of many, many key value pairs. How would I devise a regex to "add single quotes to any non-single-quoted string followed immediately by a colon" in vim?

I tried the regex found here but it appends an empty set of quotes after the key.

1
  • You don't need to quote the keys, only string values. – romainl Jul 24 '14 at 21:00
2

I will suppose that each of your key:value pairs is on its own line, like so:

var myObject = {
key1:val1,
key2:val2,
};

Then the following 2 regex/substitutions accomplish what you need: :%s/\(.*\):/'\1':/ followed by %s/''/'/

The first one replaces all text that precedes a colon (that's the \(.*\): part) with the same text (but surrounded by quotes) and the colon again (the '\1': part). This does not take into account any keys that are already quoted, so the second command simply replaces any set of 2 single quotes with just 1 single quote.

The first command will not work if you have multiple key:value pairs on a single line. In that case, you might try out something like :%s/, \(.*\):/, '\1':/ where there's a comma and space at the beginning of the two expressions. You'd still have to clean up the first entry in each object, since those are not preceded by commas.

Whatever command you use, I'd recommend ending it with /c, as in :%s/\(.*\):/'\1':/c so you can confirm each substitution, at least to make sure it works the way you want.

Good luck!

0
:%s/^.\{-}:\s*\zs[^',]\+/'&'

seems to do the trick:

  • ^.\{-}:\s* matches everything before the value:

     ^             | .\{-}:              | \s*
    ---------------+---------------------+--------------------
     start of line | any character,      | as much whitespace
                   | as few as possible, | as possible
                   | until the 1st colon |
    
  • \zs[^',]\+\ is our actual match. It only matches the value, basically as much as possible of any character that's not a single quote or a coma.

  • '&' replaces the match by itself surrounded by single quotes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.