Skip to content

Replacement of standard String.prototype functions causes issue in other extensions #19761

Closed
@Codeneos

Description

@Codeneos

In extensions.ts the string prototype function replaceAll is replaced by a non-standard implementation. The new implementation in this extension does not comply with the standard signature of replaceAll which causes other extension to fail.

src/client/common/extensions.ts

/**
 * String.replaceAll implementation
 * Replaces all instances of a substring with a new substring.
 */
String.prototype.replaceAll = function (this: string, substr: string, newSubstr: string): string {
    if (!this) {
        return this;
    }

    /** Escaping function from the MDN web docs site
     * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#escaping
     * Escapes all the following special characters in a string . * + ? ^ $ { } ( ) | \ \\ */

    function escapeRegExp(unescapedStr: string): string {
        return unescapedStr.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
    }

    return this.replace(new RegExp(escapeRegExp(substr), 'g'), newSubstr);
};

This will fail when the substr argument is a RegExp; but the etandard spec defined that replaceAll should accept a RegExp.

But apart from the correctness of the replacement no extension should replace a functions oon common prototypes such as string.

Would it be possible to revert this and instead use a custom extension function?

export function replaceAll(this: string, substr: string, newSubstr: string);

-or-

export function replaceSubstring(this: string, substr: string, newSubstr: string);

Metadata

Metadata

Assignees

Labels

triage-neededNeeds assignment to the proper sub-team

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions