@developit/replaceall

1.0.0 • Public • Published

76b ponyfill for String.prototype.replaceAll().

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);
  };
}

Readme

Keywords

none

Package Sidebar

Install

npm i @developit/replaceall

Weekly Downloads

0

Version

1.0.0

License

MIT

Unpacked Size

3.29 kB

Total Files

6

Last publish

Collaborators

  • developit