检查文本是否为HTML

编程入门 行业动态 更新时间:2024-10-11 19:15:48
本文介绍了检查文本是否为HTML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在使用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()。

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

本文发布于:2023-11-10 14:33:42,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1575639.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文本   HTML

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!