0

I need to check if html is valid. Basically I need to check in string whether they closed or not. But I don't even know where to start.

Rules:

  • It should return true if the string is valid, and false if it's invalid.
  • All input strings will be nonempty, and will only consist of these html tags: .

Expected result

"<div></div>"   =>  True
"<div><span></span></div>"   =>  True
"<div></span>"       =>  False
"<div>"     =>  False
"<div><div><span></span></div></h1>" =>  False

So far I only have bare-bones. My Thoughts:

  1. I tried to split all tag elements into different array. Using this This answer. But that answer didn't worked for me, and I can't select empty space because there is isn't any.
  2. After splitting I would probably use for loops with if statement to compare this. Because it's only 3 tags I don't need anything fancy.

    const isHTMLValid = (html) => { 
    html = html.replace(/>/gi, ",>");
    html = html.split(',');
    console.log(html);
    
    }
    isHTMLValid("<div></div>");
    isHTMLValid("<div><span></span></div>");
    isHTMLValid("<div></span>");
    isHTMLValid("<div>");
    isHTMLValid("<div><div><span></span></div></h1>");
    
Arnas Dičkus
  • 522
  • 1
  • 10
  • 26
  • 2
    There is much more to valid HTML than just proper nesting. Is the nesting all you want to check? – str Mar 05 '19 at 13:21
  • 1
    The cool thing about browsers is that they have [a built-in HTML parser](https://developer.mozilla.org/en-US/docs/Web/API/DOMParser). Maybe use that? – Heretic Monkey Mar 05 '19 at 13:22
  • Just to add to what @str said, consider the tag `
    ` - this is *valid* HTML but there is no nesting involved. And the tag `
    ` is equally valid.
    – VLAZ Mar 05 '19 at 13:22
  • Yes, i need only proper nesting. – Arnas Dičkus Mar 05 '19 at 13:22
  • [https://validator.w3.org/](https://validator.w3.org/) – Olafant Mar 05 '19 at 13:23
  • 1
    Yes, [This question](https://stackoverflow.com/questions/10026626/check-if-html-snippet-is-valid-with-javascript) worked for me. I read it before just didn't think that it would work in this case. Expected to do something more difficult. – Arnas Dičkus Mar 05 '19 at 13:33

0 Answers0