检查文本是否为 HTML

Check if a text is HTML or not

本文关键字:HTML 是否 文本 检查      更新时间:2023-09-26

我正在使用Meteor,我正在尝试检查文本是否为html。但是通常的方法不起作用。这是我的代码:

post: function() {
    var postId = Session.get("postId");
    var post = Posts.findOne({
        _id: postId
    });
    var object = new Object();
    if (post) {
        object.title = post.title;
        if ($(post.content).has("p")) { //$(post.content).has("p") / post.content instanceof HTMLElement

            object.text = $(post.content).text();

            if (post.content.match(/<img src="(.*?)"/)) {
                object.image = post.content.match(/<img src="(.*?)"/)[1];
            }
        } else {
            console.log("it is not an html------------------------");
            object.text = post.content;
        }
    }
    return object;
}

实际上,这是我迄今为止使用过的最"有效"的解决方案。另外,我指出了我使用的两种最常见的方式(在if语句旁边)。没有正则表达式是否有可能发生。

可以使用你已经开始使用jQuery的方法,但将响应附加到新<div>并检查该元素是否有子元素。如果jQuery找到子项,则它是html。

如果是 html,您可以使用 find() 在该div 中搜索任何类型的元素。

// create element and inject content into it
var $div=$('<div>').html(post.content);
// if there are any children it is html
if($div.children().length){
   console.log('this is html');
   var $img = $div.find('img');
   console.log('There are ' + $img.length +' image(s)');
}else{
   console.log('this is not html');
}

使用 jquery $.parseHTML 函数将字符串解析为 DOM 节点数组,并检查它是否有任何 HTMLElement。

var htmlText = "----<b>abc</b>----<h3>GOOD</h3>----";
htmlText = prompt("Please enter something:", "----<b>abc</b>----");
var htmlArray = $.parseHTML(htmlText);
var isHtml = htmlArray.filter(function(e){ return e instanceof HTMLElement;}).length;
console.log(htmlText);
//console.log(htmlArray);
if (isHtml)
  console.log(isHtml + " HTML Element(s) found.");
else
  console.log("No HTML Elements found!");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>