[英]jQuery remove certain tags from a string
I have a string where I want to remove all figure tags. 我有一个要删除所有图形标签的字符串。 I have tried the following:
我尝试了以下方法:
var s = '<html><body>report content<figure id="fig2" data-contenttype="chart"><img src="chart.jpg"/><div>chart 1</div></figure><div>body content</div><figure id="fig2"><img src="chart2.jpg"/><div>chart 2</div></figure></body></html>';
var result = $(s).find('figure').remove();
The reason this does not work is that find does not find the figure elements because they have children. 这样做不起作用的原因是find找不到图形元素,因为它们有孩子。 Does anyone know how I can remove all figure nodes (and everything inside them) and leave the rest of the html in tact?
有谁知道我如何删除所有的数字节点(以及其中的所有内容),并保持其余的html完好无损?
Note the html is not in the DOM I need to do this via string manipulation. 注意html不在DOM中,我需要通过字符串操作来做到这一点。 I don't want to touch the DOM.
我不想碰DOM。
You can wrap your string
in a jQuery object and do some sort of a manipulation like this: 您可以将
string
包装在jQuery对象中,并进行如下操作:
var removeElements = function(text, selector) {
var wrapped = $("<div>" + text + "</div>");
wrapped.find(selector).remove();
return wrapped.html();
}
USAGE 用法
var removedString = removeElements('<html><body>report content<figure id="fig2" data-contenttype="chart"><img src="chart.jpg"/><div>chart 1</div></figure><div>body content</div><figure id="fig2"><img src="chart2.jpg"/><div>chart 2</div></figure></body></html>','figure');
The beauty of this approach is that you can specify a jquery selector which to remove. 这种方法的优点在于,您可以指定要删除的jquery选择器。
Another approach for keeping html and body tag: 保留html和body标签的另一种方法:
var s = '<html><body>report content<figure id="fig2" data-contenttype="chart"><img src="chart.jpg"/><div>chart 1</div></figure><div>body content</div><figure id="fig2"><img src="chart2.jpg"/><div>chart 2</div></figure></body></html>';
var $s = s.replace(/<figure>(.*)<\/figure>/g, "");
console.log($s)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.