From 8f9b6534c64dd871db92729714b46d400a52e30e Mon Sep 17 00:00:00 2001 From: toasted-nutbread Date: Sat, 7 Mar 2020 15:23:32 -0500 Subject: Move stringReplaceAsync It is only used in AnkiNoteBuilder and it was originally created for this purpose. --- ext/bg/js/anki-note-builder.js | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) (limited to 'ext/bg/js') diff --git a/ext/bg/js/anki-note-builder.js b/ext/bg/js/anki-note-builder.js index be39ff43..2a15b20d 100644 --- a/ext/bg/js/anki-note-builder.js +++ b/ext/bg/js/anki-note-builder.js @@ -93,7 +93,7 @@ class AnkiNoteBuilder { }; const markers = this._markers; const pattern = /\{([\w-]+)\}/g; - return await stringReplaceAsync(field, pattern, async (g0, marker) => { + return await AnkiNoteBuilder.stringReplaceAsync(field, pattern, async (g0, marker) => { if (!markers.has(marker)) { return g0; } @@ -106,4 +106,19 @@ class AnkiNoteBuilder { } }); } + + static stringReplaceAsync(str, regex, replacer) { + let match; + let index = 0; + const parts = []; + while ((match = regex.exec(str)) !== null) { + parts.push(str.substring(index, match.index), replacer(...match, match.index, str)); + index = regex.lastIndex; + } + if (parts.length === 0) { + return Promise.resolve(str); + } + parts.push(str.substring(index)); + return Promise.all(parts).then((v) => v.join('')); + } } -- cgit v1.2.3