jQuery从HTML-String中移除标签 [英] jQuery remove tag from HTML-String

查看:68
本文介绍了jQuery从HTML-String中移除标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有以下字符串:

  var s ='< span>一些文字< / span>一些其他文字'; 

结果应该是一个内容为其他文字的字符串。



我试过......

$ $ $ $ $ $ $ $ $ $ $ s $ .not('跨度');

...以及其他许多与 remove() not()等,但没有任何工作。



有什么建议吗?我可以将字符串与正则表达式匹配,但我更喜欢常见的jQuery解决方案。



编辑

我做不是使用正则表达式搜索解决方案,我只是想知道为什么这个例子不起作用:
http://jsfiddle.net/q9crX/150/ 解决方案

<您可以将字符串包装到一个jQuery对象中,并执行下面的操作:

  var removeElements = function(text,selector){
var wrapped = $(< div>+ text +< / div>);
wrapped.find(selector).remove();
返回wrapped.html();
}

USAGE $ b

  var removedSpanString = removeElements(< span>一些文字< / span>其他文字,span); 

这种方法的好处在于您可以指定要删除的jquery选择器。即您可能希望删除字符串中的< th> 。在这种情况下这将非常方便。
希望这有助于!

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".

I tried...

var $s = $(s).not('span');

...and a lot of other stuff with remove(), not(), etc. but nothing worked.

Any suggestions? I could match the string with regex, but I prefer a common jQuery solution.

edit:

I do not search a solution with regex, I'm just wondering why this example does not work: http://jsfiddle.net/q9crX/150/

解决方案

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();
}

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从HTML-String中移除标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆