Skip to content

Don't change the behavior of String.prototype.replaceAll globally #17

@kevinoid

Description

@kevinoid

jgeXml unconditionally overwrites String.prototype.replaceAll with its own version, which does not handle a Function as its second argument according to the spec:

jgeXml/common.js

Lines 3 to 9 in 82cb8c7

Object.defineProperty(String.prototype,'replaceAll',{
value: function(search, replacement) {
var target = this;
return target.split(search).join(replacement);
},
enumerable: false}
);

This can break other code in the same project in interesting ways. For example, running the code

console.log('Before:', 'example'.replaceAll('e', (match, offset) => offset ? 'e!' : 'E'));
require('jgexml');
console.log('After:', 'example'.replaceAll('e', (match, offset) => offset ? 'e!' : 'E'));

prints

Before: Example!
After: (match, offset) => offset ? 'e!' : 'E'xampl(match, offset) => offset ? 'e!' : 'E'

Note that jgexml is not used or called, simply required. This is surprising and was frustrating to track down.

Could you consider not modifying String.prototype.replaceAll (or any global variables or their properties) or, if you must, only polyfilling it when absent and using a spec-conformant polyfill?

Thanks for considering,
Kevin

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions