VimL string index

24 views
Skip to first unread message

Mark Volkmann

unread,
May 4, 2015, 6:39:16 AM5/4/15
to vim...@googlegroups.com
I don't see a builtin function to find the index of a substring within a string.
Does that exist?
For example, I want something like index('foobarbaz', 'bar') to return 3.
It seems the index function works on lists, but not strings.

---
R. Mark Volkmann
Object Computing, Inc.

Jürgen Krämer

unread,
May 4, 2015, 7:18:25 AM5/4/15
to vim...@googlegroups.com

Hi,

Mark Volkmann schrieb am 04.05.2015 um 12:39:
> I don't see a builtin function to find the index of a substring within a string.
> Does that exist?
> For example, I want something like index('foobarbaz', 'bar') to return 3.
> It seems the index function works on lists, but not strings.

the function is called stridx(). Note that it returns the *byte* index. This
might matter if you have encoding set to UTF-8 and the string in which you
want to search contains non-ASCII letters before the first occurrence of the
search string, e.g.,

:echo stridx('Jürgen', 'rg')

prints 2 if encoding is set to latin1, but prints 3 if encoding is set to
UTF-8.

Regards,
Jürgen

--
Sometimes I think the surest sign that intelligent life exists elsewhere
in the universe is that none of it has tried to contact us. (Calvin)

Marcin Szamotulski

unread,
May 4, 2015, 9:35:57 AM5/4/15
to vim...@googlegroups.com
Just check `:h string-functions`, and you'll find `stridx()`.

Best regards,
Marcin
signature.asc
Reply all
Reply to author
Forward
0 new messages