UNPKG

1.49 kBPlain TextView Raw
1declare global {
2 // https://github.com/microsoft/TypeScript/blob/main/lib/lib.es2021.string.d.ts
3 interface String {
4 /**
5 * Replace all instances of a substring in a string, using a regular expression or search string.
6 * @param searchValue A string to search for.
7 * @param replaceValue A string containing the text to replace for every successful match of searchValue in this string.
8 */
9 replaceAll(searchValue: string | RegExp, replaceValue: string): string;
10
11 /**
12 * Replace all instances of a substring in a string, using a regular expression or search string.
13 * @param searchValue A string to search for.
14 * @param replacer A function that returns the replacement text.
15 */
16 replaceAll(
17 searchValue: string | RegExp,
18 replacer: (substring: string, ...args: any[]) => string,
19 ): string;
20 }
21}
22
23/**
24 * String.prototype.replaceAll() polyfill
25 * https://gomakethings.com/how-to-replace-a-section-of-a-string-with-another-one-with-vanilla-js/
26 * @author Chris Ferdinandi
27 * @license MIT
28 */
29if (!String.prototype.replaceAll) {
30 String.prototype.replaceAll = function (str: any, newStr: any) {
31 // If a regex pattern
32 if (
33 Object.prototype.toString.call(str).toLowerCase() === "[object regexp]"
34 ) {
35 return this.replace(str, newStr);
36 }
37
38 // If a string
39 return this.replace(new RegExp(str, "g"), newStr);
40 };
41}
42
43export {};
44declare global {
45 interface Error {
46 cause?: any;
47 }
48}
49
50export {};