Check if HTML snippet is valid with Javascript

前端 未结 7 1978
忘了有多久
忘了有多久 2020-11-29 05:03

I need a reliable Javascript library / function to check if a HTML snippet is valid that I can call from my code. For example, it should check that opened tags and quotation

7条回答
  •  野性不改
    2020-11-29 05:39

    function validHTML(html) {
      var openingTags, closingTags;
    
      html        = html.replace(/<[^>]*\/\s?>/g, '');      // Remove all self closing tags
      html        = html.replace(/<(br|hr|img).*?>/g, '');  // Remove all 
    ,
    , and tags openingTags = html.match(/<[^\/].*?>/g) || []; // Get remaining opening tags closingTags = html.match(/<\/.+?>/g) || []; // Get remaining closing tags return openingTags.length === closingTags.length ? true : false; } var htmlContent = "

    your html content goes here

    " // Note: String without any html tag will consider as valid html snippet. If it’s not valid in your case, in that case you can check opening tag count first. if(validHTML(htmlContent)) { alert('Valid HTML') } else { alert('Invalid HTML'); }

提交回复
热议问题