-
-
Save benjamin-frazier/24f4a14cf9f0c9447d1f8e12055ef57c to your computer and use it in GitHub Desktop.
s:substring() and s:substring_once() in vital.vim
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
" Substitute a:from => a:to by string. | |
" To substitute by pattern, use substitute() instead. | |
function! s:substring(str, from, to) | |
if a:str ==# '' || a:from ==# '' | |
return a:str | |
endif | |
let str = a:str | |
let idx = stridx(str, a:from) | |
while idx !=# -1 | |
let left = idx ==# 0 ? '' : str[: idx - 1] | |
let right = str[idx + strlen(a:from) :] | |
let str = left . a:to . right | |
let idx = stridx(str, a:from) | |
endwhile | |
return str | |
endfunction | |
" Substitute a:from => a:to only once. | |
" cf. s:substring() | |
function! s:substring_once(str, from, to) | |
if a:str ==# '' || a:from ==# '' | |
return a:str | |
endif | |
let idx = stridx(a:str, a:from) | |
if idx ==# -1 | |
return a:str | |
else | |
let left = idx ==# 0 ? '' : a:str[: idx - 1] | |
let right = a:str[idx + strlen(a:from) :] | |
return left . a:to . right | |
endif | |
endfunction | |
" foar | |
echom s:substring('foobar', 'ob', '') | |
" bar | |
echom s:substring('foobar', 'foo', '') | |
" foob | |
echom s:substring('foobar', 'ar', '') | |
" | |
echom s:substring('', 'foo', '') | |
" foobar | |
echom s:substring('foobar', '', '') | |
" foobarbaz | |
" echom s:substring('foobar', 'bar', 'barbaz') | |
" foobaz | |
echom s:substring('foobar', 'bar', 'baz') | |
echom '---' | |
" foar | |
echom s:substring_once('foobar', 'ob', '') | |
" bar | |
echom s:substring_once('foobar', 'foo', '') | |
" foob | |
echom s:substring_once('foobar', 'ar', '') | |
" | |
echom s:substring_once('', 'foo', '') | |
" foobar | |
echom s:substring_once('foobar', '', '') | |
" foobarbaz | |
echom s:substring_once('foobar', 'bar', 'barbaz') | |
" foobaz | |
echom s:substring_once('foobar', 'bar', 'baz') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment