检查文本是否为HTML [英] Check if a text is HTML or not
问题描述
我正在使用Meteor,我正在尝试检查文本是否为html。但通常的方法不起作用。这是我的代码:
I am using Meteor and I am trying to check if a text is html. But usual ways do not work. This is my code:
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语句旁边)。是否有可能在没有正则表达式的情况下发生。
Actually, this is the most "working" solution I have used up to now. Also, I pointed out the two most common ways which I use (next to the if statement). Is it possible to happen without regex.
推荐答案
可以使用已经开始使用jQuery的方法但是将响应添加到新的< div>
并检查该元素是否包含子元素。如果jQuery找到孩子它是html。
Can use approach you already started with jQuery but append response to a new <div>
and check if that element has children. If jQuery finds children it is html.
如果它是html,那么你可以使用 find()搜索该div的任何类型的元素code>。
If it is html you can then search that div for any type of element using 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');
}
这篇关于检查文本是否为HTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!