Skip to content

Instantly share code, notes, and snippets.

@developit
Last active October 11, 2020 23:32
Show Gist options
  • Save developit/1a40a6fee65361d1182aaa22ab8c334c to your computer and use it in GitHub Desktop.
Save developit/1a40a6fee65361d1182aaa22ab8c334c to your computer and use it in GitHub Desktop.
~80b ponyfill for String.prototype.replaceAll()

@developit/replaceall NPM

~80b ponyfill for String.prototype.replaceAll() with good performance.

Why ponyfill? Because this is a proposal for a spec, and polyfilling it in-place before it gets solidified could break code that relies on an incorrect implementation.

Alternate Version

This version trades a bit of size and performance for reduced memory usage.

const replaceAll = ''.replaceAll
  ? (str, find, rep) => str.replaceAll(find, rep)
  : (str, find, rep) => {
    let s = '', index, next;
    while (~(next = str.indexOf(find, index))) {
      s += str.substring(index, next) + rep;
      index = next + find.length;
    }
    return s + str.substring(index);
  }
See Polyfill Version

Don't use this, for the reason explained above.

if (!String.prototype.replaceAll) {
  String.prototype.replaceAll = function(find, replace) {
    return this.split(find).join(replace);
  };
}
if (!String.prototype.replaceAll) {
  String.prototype.replaceAll = function(find, replace) {
    let s = '', index, next;
    while (~(next = this.indexOf(find, index))) {
      s += this.substring(index, next) + replace;
      index = next + find.length;
    }
    return s + this.substring(index);
  };
}
{
"name": "@developit/replaceall",
"version": "1.0.0",
"main": "replaceall.js",
"module": "replaceall.mjs",
"author": "Jason Miller <[email protected]>",
"license": "MIT",
"scripts": {
"prepack": "cp *.md README.md",
"postpack": "rm README.md"
}
}
const replaceAll = ''.replaceAll
? (str, find, rep) => str.replaceAll(find, rep)
: (str, find, rep) => str.split(find).join(rep)
module.exports=''.replaceAll?function(s,f,r){return s.replaceAll(f,r)}:function(s,f,r){return s.split(f).join(r)}
export default ''.replaceAll?(s,f,r)=>s.replaceAll(f,r):(s,f,r)=>s.split(f).join(r)
@OliverBalfour
Copy link

This implementation is not fully standards compliant. MDN says here that the replacement can be a function which takes the RegExp match as input.

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