I know I can use regex matching with ~= and that stridx(haystack, needle) == 0 does work, but if I just want to verify that one string starts with another, I don't want to waste resources checking the rest of the haystack, which stridx will do.

What's the fastest way to compare the beginning of the string? I have my own answer below, but I suspect it can be done even better, perhaps by not creating a temporary string but by directly indexing the two strings?


1 Answer 1

fu! StartsWith(longer, shorter) abort
  return a:longer[0:len(a:shorter)-1] ==# a:shorter

And the converse:

fu! EndsWith(longer, shorter) abort
  return a:longer[len(a:longer)-len(a:shorter):] ==# a:shorter

You may also need contains:

fu! Contains(longer, shorter) abort
  return stridx(a:longer, a:short) >= 0

Your Answer

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

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