Skip to content

Instantly share code, notes, and snippets.

@LukeTully
Created November 23, 2016 04:02
Show Gist options
  • Save LukeTully/2cef782a88ba63c72dadabf8adbbacd8 to your computer and use it in GitHub Desktop.
Save LukeTully/2cef782a88ba63c72dadabf8adbbacd8 to your computer and use it in GitHub Desktop.
// String replacement with index constraints
function replaceBetween(startIndex, endIndex, search, replace, text) {
// Portion of text up until the section we want to search in
var firstChunk = text.slice(0, startIndex);
var lastChunk = (endIndex !== text.length - 1) ? text.slice(endIndex, text.length) : "";
// Create the string to search within
var searchableText = text.slice(startIndex, endIndex);
// Replace the text
var newText = searchableText.replace(search, replace);
// Piece together the result
return firstChunk + newText + lastChunk;
}
@LukeTully
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment