Created
August 14, 2016 21:33
-
-
Save Songbird0/22d6539e99666b11ad2bd5176677b2bf to your computer and use it in GitHub Desktop.
replace_word function for javascript developers. See original function here: https://gist.github.com/Songbird0/978bf046b37a2969c51495336c7c29ef
This file contains 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
function replace_word(initial_string, word, newWord) { | |
var index = initial_string.indexOf(word); | |
if (index !== -1) { | |
var first_part = ''; | |
var mid_part = ''; | |
var second_part = ''; | |
if (index === 0) { | |
first_part = newWord; | |
second_part = sliceAt(initial_string, word); | |
return "" + first_part + second_part; | |
} | |
if (index === (initial_string.length - 1)) { | |
first_part = sliceAt(initial_string, word); | |
second_part = newWord; | |
return "" + first_part + second_part; | |
} | |
if (index > 0 && index < (initial_string.length - 1)) { | |
var word_length = word.length; | |
first_part = initial_string.substring(0, index); | |
mid_part = newWord; | |
second_part = initial_string.substring(index + word_length); | |
return "" + first_part + mid_part + second_part; | |
} | |
} | |
return null; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment