-1

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.

Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
Jayamurugan
  • 1,757
  • 2
  • 14
  • 34
  • 1
    Please show what you have tried. At the moment this is a 'write my code for me' request, which will be downvoted and closed. Also, how are you going to determine what is/is not valid? By your logic (anything which doesn't have a closing tag should be removed) the `` element will be removed as it doesn't have a closing tag - yet is perfectly valid. – Rory McCrossan May 11 '16 at 06:52
  • No is valid – Jayamurugan May 11 '16 at 07:02
  • Thats exactly my point. – Rory McCrossan May 11 '16 at 07:02

1 Answers1

1

Using jQuery you can do something like this with help of replace()

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(); // encoding matched text
  })
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

Regex explanation here

Regular expression visualization


Refer the following answer for html encoding : HTML-encoding lost when attribute read from input field

Community
  • 1
  • 1
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188