我想确定一个字符串是否包含一个未被“<>”括起来的子字符串。例如,
<image src=abc> -> false
<image src=abc><image src=def> -> false
<tag>hello</tag> -> true
<image src=abc>hello -> true
我知道我可以做到以下几点:
!_.isEmpty(String(input).replace(/<[^>]+>/gm, ''))
, 但想知道是否有更好的方法,使用 regex.test
最佳答案
将HTML字符串转成文档,然后将文档的.textContent
取出来,裁剪一下,看是否为空:
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>'));
当您可以解析 DOM 时,不要使用正则表达式。
关于javascript - HTML 标签的 RegExp.test,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66149120/