Advertisement
Koragg

Check If HTML Code Is Valid [JavaScript]

Feb 4th, 2020
165
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <textarea id="text" rows="5" cols="50">
  2. <b>At</b> <a href="https://www.w3schools.com">w3schools.com</a> you'll learn how to make a <sup>website</sup>. 5 < 6!
  3. </textarea>
  4.  
  5. <script>
  6.   // https://stackoverflow.com/questions/10026626/check-if-html-snippet-is-valid-with-javascript
  7.   // https://stackoverflow.com/questions/6093986/replace-all-strings-and-in-a-variable-with-lt-and-gt
  8.   var text = document.getElementById('text');
  9.   var textValue = text.value;
  10.   function checkHTML(html) {
  11.        var doc = document.createElement('div');
  12.        doc.innerHTML = html;
  13.        return doc.innerHTML === html;
  14.    }
  15.   var fixedTextValue = textValue.replace(/\</g,"&lt;").replace(/\>/g,"&gt;") // convert < and > to &lt; and &gt;
  16.   // restore opening tags
  17.   .replace(/&lt;b&gt;/g,"<b>").replace(/&lt;sup&gt;/g,"<sup>").replace(/&lt;sub&gt;/g,"<sub>")
  18.   .replace(/&lt;a/g,"<a").replace(/\"&gt;/g,"\">")
  19.   // restore closing tags
  20.   .replace(/&lt;\/b&gt;/g,"</b>").replace(/&lt;\/sup&gt;/g,"</sup>").replace(/&lt;\/sub&gt;/g,"</sub>")
  21.   .replace(/&lt;\/a&gt;/g,"<\/a>");
  22.   alert(textValue + '\n\nvalid? ' + checkHTML(textValue));
  23.   alert(fixedTextValue + '\n\nvalid? ' + checkHTML(fixedTextValue));
  24.   // inputted text can contain html tags and < and/or > symbols
  25.   // convert inputted text to fixed one before validating html
  26.   // this way if we have < and/or > it will still be valid html as only < will be replaced by &lt; and > - by &gt;
  27.   // the replacing will be done behind the scenes, will not be set to textarea value! Needed only to check HTML!
  28. </script>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement