检查文本是否为HTML

Ste*_*L19 4 html javascript jquery meteor

我正在使用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;
}
Run Code Online (Sandbox Code Playgroud)

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

cha*_*tfl 7

可以使用已经开始使用jQuery的方法,但是将响应附加到new <div>并检查该元素是否有子元素.如果jQuery找到孩子,那就是html.

如果它是html,那么你可以使用搜索任何类型元素的div find().

// 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');
}
Run Code Online (Sandbox Code Playgroud)