JqueryRock JqueryRock - 2 years ago 74
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>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download