General: Leverage DOMParser to implement wp.sanitize.stripTags().

Developed in https://github.com/WordPress/wordpress-develop/pull/10536

Follow-up to [60907].

Props hbhalodia, dmsnell, westonruter.
See #48054.
Fixes #64274.

Built from https://develop.svn.wordpress.org/trunk@61347


git-svn-id: http://core.svn.wordpress.org/trunk@60659 1a063a9b-81f0-0310-95a4-ce76da25c4cd
This commit is contained in:
Weston Ruter
2025-12-03 18:09:33 +00:00
parent 9d0d7c1b18
commit 9c36fe9b4d
3 changed files with 18 additions and 15 deletions

View File

@@ -23,22 +23,25 @@
* @return {string} Stripped text.
*/
stripTags: function( text ) {
let _text = text || '';
const domParser = new DOMParser();
const htmlDocument = domParser.parseFromString(
text,
'text/html'
);
// Do the search-replace until there is nothing to be replaced.
do {
// Keep pre-replace text for comparison.
text = _text;
// Do the replacement.
_text = text
.replace( /<!--[\s\S]*?(-->|$)/g, '' )
.replace( /<(script|style)[^>]*>[\s\S]*?(<\/\1>|$)/ig, '' )
.replace( /<\/?[a-z][\s\S]*?(>|$)/ig, '' );
} while ( _text !== text );
/*
* The following self-assignment appears to be a no-op, but it isn't.
* It enforces the escaping. Reading the `innerText` property decodes
* character references, returning a raw string. When written, however,
* the text is re-escaped to ensure that the rendered text replicates
* what it's given.
*
* See <https://github.com/WordPress/wordpress-develop/pull/10536#discussion_r2550615378>.
*/
htmlDocument.body.innerText = htmlDocument.body.innerText;
// Return the text with stripped tags.
return _text;
return htmlDocument.body.innerHTML;
},
/**

View File

@@ -1,2 +1,2 @@
/*! This file is auto-generated */
window.wp=window.wp||{},wp.sanitize={stripTags:function(t){let e=t||"";for(;(e=(t=e).replace(/<!--[\s\S]*?(-->|$)/g,"").replace(/<(script|style)[^>]*>[\s\S]*?(<\/\1>|$)/gi,"").replace(/<\/?[a-z][\s\S]*?(>|$)/gi,""))!==t;);return e},stripTagsAndEncodeText:function(t){let e=wp.sanitize.stripTags(t),i=document.createElement("textarea");try{i.textContent=e,e=wp.sanitize.stripTags(i.value)}catch(t){}return e}};
window.wp=window.wp||{},wp.sanitize={stripTags:function(t){t=(new DOMParser).parseFromString(t,"text/html");return t.body.innerText=t.body.innerText,t.body.innerHTML},stripTagsAndEncodeText:function(t){let e=wp.sanitize.stripTags(t),n=document.createElement("textarea");try{n.textContent=e,e=wp.sanitize.stripTags(n.value)}catch(t){}return e}};

View File

@@ -16,7 +16,7 @@
*
* @global string $wp_version
*/
$wp_version = '7.0-alpha-61346';
$wp_version = '7.0-alpha-61347';
/**
* Holds the WordPress DB revision, increments when changes are made to the WordPress DB schema.