Sometimes, we want to check if a string is HTML or not with JavaScript.
In this article, we’ll look at how to check if a string is HTML or not with JavaScript.
How to check if a string is HTML or not with JavaScript?
To check if a string is HTML or not with JavaScript, we check if there’re any tags present in the string.
For instance, we write
const isHtml = /<\/?[a-z][\s\S]*>/i.test("<p>fizz buzz</p>");
to call /<\/?[a-z][\s\S]*>/i.test
with "<p>fizz buzz</p>"
to check if "<p>fizz buzz</p>"
is a JavaScript string.
We use <\/?[a-z][\s\S]*>
to check for any tags in the string to check if it has any HTML markup.
[a-z]
checks for letters and \s\S
checks for spaces and non-space characters.
Conclusion
To check if a string is HTML or not with JavaScript, we check if there’re any tags present in the string.