Remove tag but leave contents - jQuery/Javascript
I'm a bit tired tonight and just can't really think how to do this simply. Basically, I have something similar to the below and I want to strip out html tags but leave their contents:
<a href="#">some content</a> and more <a hr开发者_开发问答ef="#"> and more content</a>
and actually return the following:
some content and more and more content
Any help as always - massively appreciated!
EDIT: Thank you all so much for the answers - there I was going down the regular expression route, way to over complicate things! I actually ended up using .text() as suggested below, I've used this before but only to set, never to retrieve and it worked better as I was returning quite a large object! Thank you so much for all the suggestions :). I'll accept the answer after 6 minutes.
$(
'a'
)
.contents()
.unwrap()
Fiddle
$(selector).text() should strip out all the html.
This way is a little longer but maybe more self explanatory than the contents()
method.
$('a').each(function () {
$(this).replaceWith($(this).html())
})
replaceWith
accepts replacement html. (not selectors)
You can write
$(...).find('*')
.replaceWith(function() { return this.childNodes });
I don't know how well this will handle nested tags.
Perhaps something like this:
jQuery.fn.stripTags = function() {
return this.replaceWith( this.html().replace(/<\/?[^>]+>/gi, '') );
};
Source: http://www.mail-archive.com/jquery-en@googlegroups.com/msg18843.html
精彩评论