Reputation: 193
I'd like to determine if a string contains a substring not enclosed by "<>". For example,
<image src=abc> -> false
<image src=abc><image src=def> -> false
<tag>hello</tag> -> true
<image src=abc>hello -> true
I know I can do the following:
!_.isEmpty(String(input).replace(/<[^>]+>/gm, ''))
, but wondering if there's a better way, using regex.test
Upvotes: 3
Views: 59
Reputation: 370729
Turn the HTML string into a document, then take the document's .textContent
, trim it, and see if it's empty:
const hasContent = str => new DOMParser().parseFromString(str, 'text/html').body.textContent.trim() !== '';
console.log(hasContent('<image src=abc><image src=def>'));
console.log(hasContent('<tag>hello</tag>'));
Don't use a regex when you can parse the DOM.
Upvotes: 1