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