1

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

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Same here. Am I doing something wrong with your code? jsfiddle.net/PQfex/3
@Kluska000 Yeah, you also had a $ in your regex that you don't want. I removed it too.
2
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.

Comments

1

yep, don't use $ in:

/<\/\S+>$/

fiddle

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.