Skip to content

Instantly share code, notes, and snippets.

@tyru
Created December 15, 2010 15:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tyru/742061 to your computer and use it in GitHub Desktop.
Save tyru/742061 to your computer and use it in GitHub Desktop.
function! ReplaceSubstring(str, from, to)
let idx = stridx(a:str, a:from)
if idx == -1
return a:str
endif
let before = idx == 0 ? '' : a:str[: idx-1]
let after = a:str[idx + strlen(a:from) :]
return before . a:to . after
endfunction
" tests
SimpleTapSingleTest
Is ReplaceSubstring("foobarbaz", "foo", "hi"), "hibarbaz"
Is ReplaceSubstring("foobarbaz", "oo", "hi"), "fhibarbaz"
Is ReplaceSubstring("foobarbaz", "bar", "hi"), "foohibaz"
Is ReplaceSubstring("foobarbaz", "baz", "hi"), "foobarhi"
Is ReplaceSubstring("fooBarbaz", "ba", "hi"), "fooBarhiz"
Is ReplaceSubstring("", "foo", "hi"), ""
Is ReplaceSubstring('&\;?[a-z]%$"', "[a-z]", "foo"), '&\;?foo%$"'
Done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment