简体   繁体   中英

Is there a Regular expression to match the html string that can not render any text?

As the title shows.

const reg = //i  //what should the regular expression be?

let HTML = ''; // true

html = '<p></p>' // true
html = '<p> </p>' // true
html = '<p><p></p></p>' // true
html = '<div><br></div>' // true
html = '<div><br/></div>' // true
html = '<div>&nbsp;</div>' // true
html = '<p>a</p><p></p>' // false

reg.test(HTML)

Or are there any other methods to match the string like that?

Thank you!

Since you're using Javascript, you could turn the text into a document, then take the document's textContent , trim it, and check to see if it's the empty string:

 const test = str => new DOMParser() .parseFromString(str, 'text/html') .documentElement .textContent .trim() === ''; console.log(test('<p></p>')); // true console.log(test('<p> </p>')); // true console.log(test('<p><p></p></p>')); // true console.log(test('<div><br></div>')); // true console.log(test('<div><br/></div>')); // true console.log(test('<div>&nbsp;</div>')); // true console.log(test('<p>a</p><p></p>')); // false

( DOMParser is used instead of just assigning the HTML as the innerHTML of an element, because the innerHTML method can allow for arbitrary code execution, which is unsafe)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM