Skip to content

Instantly share code, notes, and snippets.

@tyru
Created May 21, 2011 06:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save tyru/984296 to your computer and use it in GitHub Desktop.
Save tyru/984296 to your computer and use it in GitHub Desktop.
s:substring() and s:substring_once() in vital.vim
" 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