jQuery从不带RegEx的HTML字符串中删除标签 [英] jQuery remove tag from HTML String without RegEx
问题描述
所以我有以下字符串:
var s = '<span>Some Text</span> Some other Text';
结果应为内容为其他文本"的字符串.
The result should be a string with the content "Some other Text".
我尝试过...
var $s = $(s).not('span');
...以及许多其他内容,例如remove()
,not()
等,但无济于事.
...and a lot of other stuff with remove()
, not()
, etc. but nothing worked.
有什么建议吗?我可以将字符串与正则表达式匹配,但我更喜欢通用的jQuery解决方案.
Any suggestions? I could match the string with regex, but I prefer a common jQuery solution.
我不使用正则表达式搜索解决方案,我只是想知道为什么此示例不起作用: http://jsfiddle.net/q9crX/150/
I do not search a solution with regex, I'm just wondering why this example does not work: http://jsfiddle.net/q9crX/150/
推荐答案
您可以将string
包装在jQuery对象中,并进行如下操作:
You can wrap your string
in a jQuery object and do some sort of a manipulation like this:
var removeElements = function(text, selector) {
var wrapped = $("<div>" + text + "</div>");
wrapped.find(selector).remove();
return wrapped.html();
}
用法
var removedSpanString = removeElements("<span>Some Text</span> Some other Text", "span");
此方法的优点在于,您可以指定要删除的jquery选择器.即您可能希望删除字符串中的<th>
.在这种情况下,这将非常方便.
希望这可以帮助!
The beauty of this approach is that you can specify a jquery selector which to remove. i.e. you may wish to remove the <th>
in a string. This would be very handy in that case.
Hope this helps!
这篇关于jQuery从不带RegEx的HTML字符串中删除标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!