Friday, September 5, 2025
HomeLanguagesJavascriptHow to check if a string is html or not using JavaScript?

How to check if a string is html or not using JavaScript?

The task is to validate whether the given string is valid HTML or not using JavaScript. we’re going to discuss a few techniques. 

Approach

  • Get the HTML string into a variable.
  • Create a RegExp which checks for the validation.
  • RegExp should follow the rules of creating an HTML document.

Example 1: In this example, a regexp is created and it is validating the HTML string as valid. 

html




<h1 style="color:green;" id="h1">
    neveropen
</h1>
<p id="GFG_UP">
</p>
<button onclick="GFG_Fun()">
    click here
</button>
<p id="GFG_DOWN">
</p>
<script>
    var up = document.getElementById('GFG_UP');
    var str1 = '<div>GeeksForGeeks</div>';
    var str = '<div>GeeksForGeeks</div>';
      
    up.innerHTML = "Click on the button to check "+
    "for the valid HTML.<br> String - " + str1;
      
    var down = document.getElementById('GFG_DOWN');
      
    function GFG_Fun() {
        down.innerHTML =
    /<(?=.*? .*?\/ ?>|br|hr|input|!--|wbr)[a-z]+.*?>|<([a-z]+).*?<\/\1>/i.test(str);
    }
</script>


Output:

How to check if a string is html or not using JavaScript?

How to check if a string is html or not using JavaScript?

Example 2: In this example, Here also, A regexp is created and it is validating the HTML string as invalid. 

html




<h1 style="color:green;" id="h1">
    neveropen
</h1>
<p id="GFG_UP">
</p>
<button onclick="GFG_Fun()">
    click here
</button>
<p id="GFG_DOWN">
</p>
<script>
    var up = document.getElementById('GFG_UP');
    var str1 = '<div>GeeksForGeeks</dv>';
    var str = '<div>GeeksForGeeks</dv>';
      
    up.innerHTML = "Click on the button to check "+
    "for the valid HTML.<br> String - " + str1;
      
    var down = document.getElementById('GFG_DOWN');
      
    function GFG_Fun() {
        down.innerHTML =
    /<([A-Za-z][A-Za-z0-9]*)\b[^>]*>(.*?)<\/\1>/.test(str);
    }
</script>


Output:

How to check if a string is html or not using JavaScript?

How to check if a string is html or not using JavaScript?

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!
RELATED ARTICLES

Most Popular

Dominic
32269 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6638 POSTS0 COMMENTS
Nicole Veronica
11802 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11866 POSTS0 COMMENTS
Shaida Kate Naidoo
6752 POSTS0 COMMENTS
Ted Musemwa
7027 POSTS0 COMMENTS
Thapelo Manthata
6704 POSTS0 COMMENTS
Umr Jansen
6721 POSTS0 COMMENTS