• Assume I have the following HTML string:

    Please leave a message in <a href="#comments">the comments section below</a>. Thanks!

    Now let’s assume I want to emphasize some text in the previous message. In particular, I’d like to make the following sentences in bold:

    • leave a message in the comments section
    • Thanks!

    If I do so using the Block editor, the resulting HTML is as follows:

    Please <strong>leave a message in </strong><a href="#comments"><strong>the comments section</strong> below</a>. <strong>Thanks!</strong>

    As you can see, there are three strong tags:

    • a portion of my first sentence (which is outside the a tag)
    • another portion of my first sentence (which is inside the a tag)
    • my second sentence

    Now let’s assume I want to get get all the highlighted sentences. What I want to retrieve are the original sentences:

    • leave a message in the comments section
    • Thanks!

    but accessing the textContent of strong tags would return me three sentences instead:

    • leave a message in
    • the comments section
    • Thanks!

    How can I use wp.richText to retrieve my highlighted sentences? I’m assuming this is something we can do, as the Block Editor can toggle the format of a whole sentence even if it is split in multiple nodes (as shown in the example).

Viewing 1 replies (of 1 total)
  • Unfortunately wp.richText does not currently expose an API that lets you query the rich text for all formats of a particular type.

    The Block Editor is able to toggle a format that is split between multiple nodes because it uses wp.richText.removeFormat which handles this case in a one-off manner.

    It’s very cumbersome, but we could find all of the bold sentences using the existing wp.richText APIs by iterating through each character in the text and checking whether or not that character has the bold format.

    const { create, getTextContent, getActiveFormat, charAt } = wp.richText;
    
    const value = create( {
    	html: 'Please <strong>leave a message in </strong><a href="#comments"><strong>the comments section</strong> below</a>. <strong>Thanks!</strong>'
    } );
    
    const boldSentences = [];
    let currentBoldSentence = '';
    
    const text = getTextContent( value );
    for ( let i = 0; i < text.length; ++i ) {
    	if ( getActiveFormat( { ...value, start: i, end: i } , 'core/bold' ) ) {
    		currentBoldSentence += charAt( value, i );
    	} else {
    		if ( currentBoldSentence ) {
    			boldSentences.push( currentBoldSentence );
    			currentBoldSentence = '';
    		}
    	}
    }
    
    if ( currentBoldSentence ) {
    	boldSentences.push( currentBoldSentence );
    }
    
    console.log( boldSentences );
    
Viewing 1 replies (of 1 total)

The topic ‘How to extract text in HTML node using wp.richtText’ is closed to new replies.