jQuery jQuery从没有正则表达式的HTML字符串中删除标签
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12109946/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery remove tag from HTML String without RegEx
提问by Fidelis
So I have following string:
所以我有以下字符串:
var s = '<span>Some Text</span> Some other Text';
The result should be a string with the content "Some other Text".
结果应该是一个内容为“Some other Text”的字符串。
I tried...
我试过...
var $s = $(s).not('span');
...and a lot of other stuff with remove()
, not()
, etc. but nothing worked.
...以及许多其他带有remove()
,等的东西not()
,但没有任何效果。
Any suggestions? I could match the string with regex, but I prefer a common jQuery solution.
有什么建议?我可以将字符串与正则表达式匹配,但我更喜欢常见的 jQuery 解决方案。
edit:
编辑:
I do notsearch a solution with regex, I'm just wondering why this example does not work: http://jsfiddle.net/q9crX/150/
我不搜索与正则表达式的解决方案,我只是想知道,为什么这个例子不起作用: http://jsfiddle.net/q9crX/150/
回答by Abdul Munim
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 removedSpanString = removeElements("<span>Some Text</span> Some other Text", "span");
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 选择器。即您可能希望删除<th>
字符串中的 。在这种情况下,这将非常方便。希望这可以帮助!
回答by yolenoyer
A very simple approach:
一个非常简单的方法:
var html = '<span>Remove <b>tags & entities</b></span>';
var noTagText = $(html).text();
// ==> noTagText = 'Remove tags & entities'
Note that it will remove tags but also html entities.
请注意,它会删除标签,但也会删除 html 实体。
回答by sp00m
This may suit your needs:
这可能适合您的需求:
<([^ >]+)[^>]*>.*?</>|<[^/]+/>
In JavaScript:
在 JavaScript 中:
$s = s.replace(/<([^ >]+)[^>]*>.*?<\/>|<[^\/]+\/>/ig, "");
It also removes self-closing tags (e.g. <br />
).
它还删除自闭合标签(例如<br />
)。
回答by Pranay Rana
回答by Jayendra
回答by Conrad Lotz
Just do the following:
只需执行以下操作:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("span").not("span div").each(
function(index, element) {
$("span").remove();
}
);
});
</script>
<span>Some Text</span> Some other Text