Skip to content

Instantly share code, notes, and snippets.

@Songbird0
Created August 14, 2016 21:33
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 Songbird0/22d6539e99666b11ad2bd5176677b2bf to your computer and use it in GitHub Desktop.
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
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