Make WordPress Core

Changeset 60907

Timestamp:
10/06/2025 11:44:48 PM (3 days ago)
Author:
westonruter
Message:

General: Optimize wp.sanitize.stripTags() to improve memory usage.

This updates the logic to use iteration instead of recursive calls, resulting in reduced memory usage and avoiding a possible stack overflow for large HTML documents.

The JS code is also tidied up with improved JSDoc and utilizing let instead of var.

Props jrchamp, sabernhardt, SirLouen, rollybueno, mukesh27, flixos90, westonruter.
Fixes #48054.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/js/_enqueues/wp/sanitize.js

    r59714 r60907  
    22 * @output wp-includes/js/wp-sanitize.js
    33 */
     4
     5/* eslint-env es6 */
    46
    57( function () {
     
    1719         * Strip HTML tags.
    1820         *
    19          * @param {string} text Text to strip the HTML tags from.
     21         * @param {string} text - Text to strip the HTML tags from.
    2022         *
    21          * @return Stripped text.
     23         * @return {string} Stripped text.
    2224         */
    2325        stripTags: function( text ) {
    24             text = text || '';
     26            let _text = text || '';
    2527
    26             // Do the replacement.
    27             var _text = text
     28            // Do the search-replace until there is nothing to be replaced.
     29            do {
     30                // Keep pre-replace text for comparison.
     31                text = _text;
     32
     33                // Do the replacement.
     34                _text = text
    2835                    .replace( /<!--[\s\S]*?(-->|$)/g, '' )
    2936                    .replace( /<(script|style)[^>]*>[\s\S]*?(<\/\1>|$)/ig, '' )
    3037                    .replace( /<\/?[a-z][\s\S]*?(>|$)/ig, '' );
    31 
    32             // If the initial text is not equal to the modified text,
    33             // do the search-replace again, until there is nothing to be replaced.
    34             if ( _text !== text ) {
    35                 return wp.sanitize.stripTags( _text );
    36             }
     38            } while ( _text !== text );
    3739
    3840            // Return the text with stripped tags.
     
    4345         * Strip HTML tags and convert HTML entities.
    4446         *
    45          * @param {string} text Text to strip tags and convert HTML entities.
     47         * @param {string} text - Text to strip tags and convert HTML entities.
    4648         *
    47          * @return Sanitized text. False on failure.
     49         * @return {string} Sanitized text.
    4850         */
    4951        stripTagsAndEncodeText: function( text ) {
    50             var _text = wp.sanitize.stripTags( text ),
     52            let _text = wp.sanitize.stripTags( text ),
    5153                textarea = document.createElement( 'textarea' );
    5254
Note: See TracChangeset for help on using the changeset viewer.