0

I want to check if the string contains html:

const containsHTML = (str) => /<[a-z][\s\S]*>/i.test(str);
console.log(containsHTML('<br>s')) // expect false

In my case i expect false, because s is not wrapped with HTML tag. How to fix the code?

Asking
  • 3,487
  • 11
  • 51
  • 106
  • Well your reg exp matches the br tag and says it is fine. Nothing stating the whole line needs to match. – epascarello Nov 01 '21 at 17:42
  • 1
    obligatory link to https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454 – epascarello Nov 01 '21 at 17:42
  • HTML supports plain text nodes... Don't see why you consider `s` is not allowed after `
    `?
    – trincot Nov 01 '21 at 17:42
  • @epascarello, so how to avoid situations if the string is not wrapped in html, could you help please? In the above situation i need to get false – Asking Nov 01 '21 at 17:46
  • Depends what it's for. If you're looking to make sure the person didn't add html before doing something like `myContainer.innerHTML = stringFromUser` then most browsers will add missing end tags anyway, so just an opening tag is enough to "get html". – James Nov 01 '21 at 17:50

1 Answers1

1

You could try this: /<([a-z]+.*)>.*<\/\1>/i

const containsHTML = (str) => /<([a-z]+.*)>.*<\/\1>/i.test(str)

console.log(containsHTML('<br>s'))    // expect false
console.log(containsHTML('<p>s</p>')) // expect true
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132