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

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

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

解决方法

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

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

  1. // load string as object,wrapped in an outer container to use for search context
  2. var o = $("<div><p>Hello World!</p><p>By Mars</p></div>");
  3.  
  4. // sets the context to only look within o; otherwise,this will return all P tags
  5. var tags = $("P",o);
  6.  
  7. tags.each(function(){
  8. var tag = $(this); // get a jQuery object for the tag
  9. // do something with the contents of the tag
  10. });

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

猜你在找的jQuery相关文章