Skip to content

Commit

Permalink
Rich Text: Eliminate second scan when getting text content (#43207)
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
dmsnell authored Aug 13, 2022
1 parent 4f53c6b commit 31fc7ed
Showing 1 changed file with 8 additions and 3 deletions.
11 changes: 8 additions & 3 deletions packages/rich-text/src/get-text-content.js
Original file line number Diff line number Diff line change
Expand Up @@ -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`.
Expand All @@ -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'
);
}

0 comments on commit 31fc7ed

Please sign in to comment.