From 31fc7ed06cfda299e5dba787b7bfb743897ebe6b Mon Sep 17 00:00:00 2001 From: Dennis Snell Date: Sat, 13 Aug 2022 22:57:56 +0200 Subject: [PATCH] Rich Text: Eliminate second scan when getting text content (#43207) When calling `getTextContent()` on a `RichTextValue` we have to make sure we replace any internal-use placeholder values. Previously we've been making two string-replace passes with a new `RegExp` on each call to `getTextContext()`. In this patch we're combining the things we want to replace into a single `RegExp` pattern so that we can make both existing substitutions in one pass through the text instead of two, and we're pre-allocating that `RegExp` at module boot time so we can avoid creating new instances of it on every call. --- packages/rich-text/src/get-text-content.js | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/packages/rich-text/src/get-text-content.js b/packages/rich-text/src/get-text-content.js index c1c23d5bccd75..17fb064eb36d8 100644 --- a/packages/rich-text/src/get-text-content.js +++ b/packages/rich-text/src/get-text-content.js @@ -8,6 +8,11 @@ import { /** @typedef {import('./create').RichTextValue} RichTextValue */ +const pattern = new RegExp( + `[${ OBJECT_REPLACEMENT_CHARACTER }${ LINE_SEPARATOR }]`, + 'g' +); + /** * Get the textual content of a Rich Text value. This is similar to * `Element.textContent`. @@ -17,7 +22,7 @@ import { * @return {string} The text content. */ export function getTextContent( { text } ) { - return text - .replace( new RegExp( OBJECT_REPLACEMENT_CHARACTER, 'g' ), '' ) - .replace( new RegExp( LINE_SEPARATOR, 'g' ), '\n' ); + return text.replace( pattern, ( c ) => + c === OBJECT_REPLACEMENT_CHARACTER ? '' : '\n' + ); }