This question may have an obvious answer that I'm missing, but how can I easily tell how many of a character, in this case " , " are in a line, or a specified string using vimscript?

2 Answers 2


VimScript does not have a special character type. In fact, you always count() for substrings (or items in list):

:echo count(getline("."), ",")

You can use this:

:echo len(split(getline('.'), ','))

That will get the content of the current line, split it on the , (comma) to a list and count the number of items of the list.

Note: that the count() function just relatively recently learned about counting items in strings, while this solution is also compatible with Vim 7.

  • 2
    Should be len(split(getline('.'), ",", 1)) - 1 as split produces more items than separators, and also to count commas at the start and the end of the line.
    – Matt
    Oct 23, 2019 at 13:01

Your Answer

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

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