javascript – 从一个字符串中删除HTML标签,使用jQuery

前端之家收集整理的这篇文章主要介绍了javascript – 从一个字符串中删除HTML标签,使用jQuery前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个简单的字符串,例如
var s = "<p>Hello World!</p><p>By Mars</p>";

如何将s转换为jQuery对象?我的目标是删除< p>和< / p> s.我可以使用正则表达式来完成它,但这是not recommended.

解决方法@H_403_8@
最简单的形式(如果我正确理解):
var s = "<p>Hello World!</p><p>By Mars</p>";
var o = $(s);
var text = o.text();

或者您可以使用具有搜索上下文的条件选择器:

// load string as object,wrapped in an outer container to use for search context
var o = $("<div><p>Hello World!</p><p>By Mars</p></div>");

// sets the context to only look within o; otherwise,this will return all P tags
var tags = $("P",o); 

tags.each(function(){
    var tag = $(this); // get a jQuery object for the tag
    // do something with the contents of the tag
});

如果您正在解析大量的HTML(例如,解释屏幕截图的结果),请使用服务器端HTML解析库,而不是jQuery(这里有关于HTML解析的帖子).

原文链接:https://www.f2er.com/jquery/152616.html

猜你在找的jQuery相关文章