JqueryRock JqueryRock - 1 year ago 51
Javascript Question

Javascript Replace trick

I am having Javascript string combinations like this,

str = "<div>xyz 123 <rd> </div>"
str = "sample text <abc>"
str = "Text <input type="text" /> new value <bla> ."

I have to find invalid tags(not having end tags) like
(<rd>, <abc>, <bla>)
and need to replace like

Can someone help to solve this. Fully in javascript.

Answer Source

Using jQuery you can do something like this

var str = `<div>xyz 123 <rd> </div>
sample text <abc>
Text <input type="text"/> new value <bla>`;

  str.replace(/<([a-z]+)([^>]*[^\/])?>(?![\s\S]*<\/\1)/gi, function(m) {
    return $('<div/>').text(m).html();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>