方法#1。这是测试字符串是否包含 HTML 数据的简单函数:
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;
}
这个想法是让浏览器 DOM 解析器决定提供的字符串是否看起来像 HTML。如您所见,它只是检查ELEMENT_NODE
( nodeType
of 1)。
我做了几个测试,看起来它有效:
isHTML('<a>this is a string</a>')
isHTML('this is a string')
isHTML('this is a <b>string</b>')
此解决方案将正确检测 HTML 字符串,但是它有副作用 img/vide/etc. 一旦在innerHTML中解析,标签将开始下载资源。
方法#2。另一种方法使用DOMParser并且没有加载资源的副作用:
function isHTML(str) {
var doc = new DOMParser().parseFromString(str, "text/html");
return Array.from(doc.body.childNodes).some(node => node.nodeType === 1);
}
注:
1.Array.from
是 ES2015 方法,可以替换为[].slice.call(doc.body.childNodes)
.
2.some
调用中的箭头函数可以替换为常用的匿名函数。