Weblurk
Weblurk

Reputation: 6812

How do I remove an element but not its content with javascript?

I have a string which is a simple <a> element.

var str = '<a href="somewhere.com">Link</a>'

Which I want to turn into:

Link

I can remove the </a> part easily with str.replace("</a>", "")but how would I remove the opening tag <a href="somewhere.com>?

Upvotes: 2

Views: 137

Answers (4)

jazZRo
jazZRo

Reputation: 1608

This will strip the whole tag:

str.replace(/<[^>]+>/g,'');

And this just the first part:

str.replace(/<[^/>]+>/g, '');

Upvotes: 3

GautamD31
GautamD31

Reputation: 28763

Use unwrap like

$('a').contents().unwrap();

But it work with the elements that are related to DOM.For your Better solution try like

 str = ($(str).text());

See this FIDDLE

Upvotes: 8

Krish R
Krish R

Reputation: 22711

Can you try this,

    var str = '<a href="somewhere.com">Link</a>';       
    alert($(str).text());

Upvotes: 0

HILARUDEEN S ALLAUDEEN
HILARUDEEN S ALLAUDEEN

Reputation: 1752

Since you are using jQuery, you can do it on the fly as follows

$('<a href="somewhere.com">Link</a>').text()

Upvotes: 2

Related Questions