Keira Nighly
Keira Nighly

Reputation: 15476

How to remove a tag, and preserved the text in the element using RegExp?

I want to remove the element tag and want to preserve the text inside the tag. I use the replace function of RegExp but it removed everything: The tag and the text inside the tag.

I dont want that, I want to remove the tag only. Clean up the text, remove the tags, I want to present the text only.

var str = str.replace(/<.>[^.]*\/.>/, "");

I used this, but there's a problem, it also removed the text inside it!

Upvotes: 1

Views: 689

Answers (3)

Matthew Flaschen
Matthew Flaschen

Reputation: 284786

Quick and dirty:

var str = "<foo>bar</foo>"; alert(str.replace(/<[^>]+>/g, ""))

Consider using real parsing and DOM manipulation instead. Correct processing of HTML using RegExp is very difficult.

Upvotes: 0

great_llama
great_llama

Reputation: 11729

If you're indeed using jQuery, and want to remove all tags, then simply set the .html() to the .text()

var e = $("#yourelement");
e.html(
    e.text()
);

Upvotes: 0

alex
alex

Reputation: 490143

what about

var obj = $('#element');

var str = obj.text();

Upvotes: 3

Related Questions