diff options
-rw-r--r-- | CHANGELOG.md | 1 | ||||
-rw-r--r-- | src/gleam_stdlib.mjs | 14 |
2 files changed, 14 insertions, 1 deletions
diff --git a/CHANGELOG.md b/CHANGELOG.md index c16bea4..e0867b3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ for empty strings on older JavaScript runtimes. - The `bool` module gains the `to_string` function. - The `function` module gains the `tap` function. +- The JavaScript implementation of the `string` module's `string_replace` received fallback code for NodeJS 14 compatibility. ## v0.20.0 - 2022-02-22 diff --git a/src/gleam_stdlib.mjs b/src/gleam_stdlib.mjs index 280cd95..4dd4aa7 100644 --- a/src/gleam_stdlib.mjs +++ b/src/gleam_stdlib.mjs @@ -58,7 +58,19 @@ export function int_to_base_string(int, base) { } export function string_replace(string, target, substitute) { - return string.replaceAll(target, substitute); + if (typeof string.replaceAll !== "undefined") { + return string.replaceAll(target, substitute); + } + // Fallback for older Node.js versions: + // 1. <https://stackoverflow.com/a/1144788> + // 2. <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#escaping> + // TODO: This fallback could be remove once Node.js 14 is EOL + // aka <https://nodejs.org/en/about/releases/> on or after 2024-04-30 + return string.replace( + // $& means the whole matched string + new RegExp(target.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'g'), + substitute + ); } export function string_reverse(string) { |