javascript - javascript检查字符串是否仅包含html
问题描述
这是我的字符串
<img class="img" src="a.png"><img class="img" src="a.png"><img class="img" src="a.png">
我想检查字符串是否只包含 html 标签
dwd<img class="img" src="a.png">dwd<img class="img" src="a.png"><img class="img" src="a.png"> dwd
如果包含类似上面示例的任何字符串,我想返回 false
我这里有一些代码可以检查一下
function isHTML(str) {
var a = document.createElement('div');
a.innerHTML = str;
for (var c = a.childNodes, i = c.length; i--; ) {
if (c[i].nodeType == 1) return true;
}
return false;
}
isHTML('<a>this is a string</a>') // true
isHTML('this is a string') // false
isHTML('this is a <b>string</b>') // true
正如我们在第三个示例中看到的那样,它返回 true 并且有一些带有 html 标签的字符串,所以如果只有 html 标签,我如何编辑它并使其返回 true 无文本
这里有另一种方法,但上面相同
var isHTML = RegExp.prototype.test.bind(/(<([^>]+)>)/i);
isHTML('Testing'); // false
isHTML('<p>Testing</p>'); // true
isHTML('<img src="hello.jpg">'); // true
isHTML('My <p>Testing</p> string'); // true (caution!!!)
isHTML('<>'); // false
它的好方法但是isHTML('My <p>Testing</p> string'); // true (caution!!!)
在这里我想返回 false 因为有一些带有 html 标签的字符串
解决方案
选项 1:使用 RegExp 和字符串替换:
const isHTML = (str) => !(str || '')
// replace html tag with content
.replace(/<([^>]+?)([^>]*?)>(.*?)<\/\1>/ig, '')
// remove remaining self closing tags
.replace(/(<([^>]+)>)/ig, '')
// remove extra space at start and end
.trim();
console.log(isHTML('Testing')); // false
console.log(isHTML('<p>Testing</p>')); // true
console.log(isHTML('<img src="hello.jpg">')); // true
console.log(isHTML('My <p>Testing</p> string')); // false
console.log(isHTML('<p>Testing</p> <p>Testing</p>')); // true
console.log(isHTML('<>')); // false
console.log(isHTML('<br>')); // true
选项 2:使用 DOM API
const isHTML = (str) => {
const fragment = document.createRange().createContextualFragment(str);
// remove all non text nodes from fragment
fragment.querySelectorAll('*').forEach(el => el.parentNode.removeChild(el));
// if there is textContent, then not a pure HTML
return !(fragment.textContent || '').trim();
}
console.log(isHTML('Testing')); // false
console.log(isHTML('<p>Testing</p>')); // true
console.log(isHTML('<img src="hello.jpg">')); // true
console.log(isHTML('My <p>Testing</p> string')); // false
console.log(isHTML('<p>Testing</p> <p>Testing</p>')); // true
console.log(isHTML('<>')); // false
console.log(isHTML('<br>')); // true
推荐阅读
- python - Python Web Scraping - 两个不同的父类名称,不同的结构但相同的子类名称
- spring - 使用 Webflux 下载文件并在浏览器中查看的更好方法
- matlab - MATLAB:如何在将图形打印到文件时为轴上的刻度定义 FontSize
- python - 将字符串中的空白映射到数字
- ios - Mac 和 IOS 14 上的 Safari 无法播放 HTML 5 MP4 视频
- javascript - 无法加载 jQuery(缩小的 jQuery 中的错误)
- python - 使用 pandas 检索一个值作为日期时间(通过按行/列过滤来选择)
- spring-security - 使用 OAuth2 的 Spring Security 多入口点
- apache-spark - 派斯帕克;在列表值上使用 ReduceByKey
- r - 选择 R 中的字符列,它们是数字