Skip to content

Commit 3865859

Browse files
committed
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. git-svn-id: https://develop.svn.wordpress.org/trunk@60907 602fd350-edb4-49c9-b593-d223f7449a82
1 parent fe2b33f commit 3865859

File tree

1 file changed

+16
-14
lines changed

1 file changed

+16
-14
lines changed

src/js/_enqueues/wp/sanitize.js

Lines changed: 16 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22
* @output wp-includes/js/wp-sanitize.js
33
*/
44

5+
/* eslint-env es6 */
6+
57
( function () {
68

79
window.wp = window.wp || {};
@@ -16,24 +18,24 @@
1618
/**
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 || '';
27+
28+
// Do the search-replace until there is nothing to be replaced.
29+
do {
30+
// Keep pre-replace text for comparison.
31+
text = _text;
2532

26-
// Do the replacement.
27-
var _text = text
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.
3941
return _text;
@@ -42,12 +44,12 @@
4244
/**
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

5355
try {

0 commit comments

Comments
 (0)