Adam Pietrasiak
Adam Pietrasiak

Reputation: 13224

JS - remove every close html tag from string

I've got such string:

var string = '<div class="post-content"></div><div class="post"></div><div id="content" class="col-lg-12"></div><div class="row"></div><div id="container" class="container"></div><body class="page page-id-157 page-template page-template-page-fullwidth-no-sidebar-php logged-in admin-bar  customize-support" style="">';

And I want to remove every close tag from it. It may or may not be div.

I've tried string.replace(/<\/\S+>$/, ''); but it seems to be working only when there is only one tag. For more it does not work at all

Fiddle here

Upvotes: 1

Views: 84

Answers (3)

vladkras
vladkras

Reputation: 17227

yep, don't use $ in:

/<\/\S+>$/

fiddle

Upvotes: 1

Paul
Paul

Reputation: 141897

You're missing the global modifier (find all matches instead of only the first), you should also make it non-greedy (Add a ? after \S+). Also remove the $ as that will only match at the end of the string:

string.replace(/<\/\S+?>/g, '');

Also note that this will remove tags like </div>, but not </ div>, since you don't allow whitespace.

Upvotes: 3

rossipedia
rossipedia

Reputation: 59427

string.replace(/<\/\S+>/g, '');

The "g" after the trailing slash means global, which means nothing more than replace all instances of the regexp, rather than the first.

Also, that $ means it will only match against the very last instance of the expression. Removing that should get what you want.

Upvotes: 2

Related Questions