检查文本是否为HTML

问题描述 投票:4回答:2

我正在使用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语句旁边)。没有正则表达式是否有可能发生。

javascript jquery html meteor
2个回答
7
投票

可以使用已经开始使用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');
}

0
投票

使用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>
© www.soinside.com 2019 - 2024. All rights reserved.