JqueryRock JqueryRock - 6 months ago 13
Javascript Question

Javascript Replace trick

I am having Javascript string combinations like this,

str = "<div>xyz 123 <rd> </div>"
or
str = "sample text <abc>"
or
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
&lt;bla&gt;


Can someone help to solve this. Fully in javascript.

Answer

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>`;


console.log(
  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>

Comments