Shluch
Shluch

Reputation: 453

JS RegExp to remove all HTML tags and their content?

For example, I need to get from this:

Before Bold <b>In Bold</b> After Bold

To get:

Before Bold After Bold.

I tried:

string.replace(/<.*>.*<\/.*>/,'')

But it don't work as expected.

Upvotes: 2

Views: 9328

Answers (3)

Marty
Marty

Reputation: 156

Try this:

string.replace(/<([^>]+?)([^>]*?)>(.*?)<\/\1>/ig, "")

It worked for me.

See it working here

Upvotes: 9

David Hellsing
David Hellsing

Reputation: 108500

I’m not sure about regex, but using jQuery you can easily just remove the children and return the HTML using a classic one-liner:

string = $('<div>').html(string).children().remove().end().html();

Upvotes: 0

VisioN
VisioN

Reputation: 145398

var div = document.createElement("div"),
    result = "",
    child;

div.innerHTML = str;
child = div.firstChild;

do {
    if (child.nodeType === 3) {
        result += child.nodeValue;
    }
} while (child = child.nextSibling);

console.log(result);

Upvotes: 1

Related Questions