Skip to content

Instantly share code, notes, and snippets.

@oneEyedSunday
Created January 25, 2020 20:21
Show Gist options
  • Save oneEyedSunday/0fbd7fa417e3d5f45e237e790722a5da to your computer and use it in GitHub Desktop.
Save oneEyedSunday/0fbd7fa417e3d5f45e237e790722a5da to your computer and use it in GitHub Desktop.
Impleenting String.replaceAll by extending the String prototype
String.prototype.replaceAll = function(candidate, replacement) {
let result = this;
let startIndex = result.indexOf(candidate);
if (startIndex < 0) {
return fullText;
}
while (startIndex > -1) {
result = replace(result, startIndex, replacement, candidate.length);
startIndex = result.indexOf(candidate);
}
return result;
}
function replace(fullText, index, replacement, length) {
return fullText.slice(0, index)
.concat(
replacement
)
.concat(fullText.slice(index + length ));
}
console.log('abcdefghiabc'.replaceAll('abc', 'iii'));
console.log('brianclausbrianclaus'.replaceAll('nc', 'aa'))
// Problems
// if replacement is a substring of string
// there is a possibility of an infinte loop
// Attempt2: Run one pass through candidate, get coords of candidate
// Then replace recursively the substr(coords) by replacement
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment