我有一个简单的字符串,例如
- var s = "<p>Hello World!</p><p>By Mars</p>";
如何将s转换为jQuery对象?我的目标是删除< p>和< / p> s.我可以使用正则表达式来完成它,但这是not recommended.
解决方法
最简单的形式(如果我正确理解):
- 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解析的帖子).