diff --git a/packages/font/src/google/loader.ts b/packages/font/src/google/loader.ts index d584742bfc4d..6a4c3a19b066 100644 --- a/packages/font/src/google/loader.ts +++ b/packages/font/src/google/loader.ts @@ -17,6 +17,18 @@ import { const cssCache = new Map>() const fontCache = new Map() +// regexp is based on https://github.com/sindresorhus/escape-string-regexp +const reHasRegExp = /[|\\{}()[\]^$+*?.-]/ +const reReplaceRegExp = /[|\\{}()[\]^$+*?.-]/g + +function escapeStringRegexp(str: string) { + // see also: https://github.com/lodash/lodash/blob/2da024c3b4f9947a48517639de7560457cd4ec6c/escapeRegExp.js#L23 + if (reHasRegExp.test(str)) { + return str.replace(reReplaceRegExp, '\\$&') + } + return str +} + const downloadGoogleFonts: FontLoader = async ({ functionName, data, @@ -124,8 +136,8 @@ const downloadGoogleFonts: FontLoader = async ({ // Replace @font-face sources with self-hosted files let updatedCssResponse = fontFaceDeclarations for (const { googleFontFileUrl, selfHostedFileUrl } of downloadedFiles) { - updatedCssResponse = updatedCssResponse.replaceAll( - googleFontFileUrl, + updatedCssResponse = updatedCssResponse.replace( + new RegExp(escapeStringRegexp(googleFontFileUrl), 'g'), selfHostedFileUrl ) }