Javascript RegExp verify string finishes with html open tag + anything but a tag

Viewed 31

I would like to verify that a string ends with any open Tag followed or not by a text

for example:

<div>some text here

or

<span>some text here

should match

but

<div>some text here</div>

or

<h1>some text here</h1>

should not

I tried to come up with a solution (sorry I'm not a regex pro)

let anyOpenTag = '<([^/>][^>])*>';
let anyCloseTag = '</[^/>][^>]*>';
let neitherOpenNorCloseTag = `[^(${anyOpenTag}|${anyCloseTag})]`;
let regex = new RegExp(
  escapeRegExp(`${anyOpenTag}${neitherOpenNorCloseTag}*$`),
  'gi');
  1. I set a variable "anyOpenTag" to a regex that verifies if it's an open tag like (<p>, <div>, <span> etc...

  2. I set a variable "anyCloseTag" to a regex that verifies if it's a closing tag like (</p>, </div>, etc...)

  3. I set a variable "neitherOpenNorCloseTag" that tries to combine the two and check if it's not one of them using the [^....]

finally I check if the regex match anyOpenTag + neitherOpenNorCloseTag

unfortunately it doesn't work for me, precisely the part that verifies "neitherOpenNorCloseTag"

your help is appreciated, even if you have a better regex I would be grateful

1 Answers

Based on your examples, this snippet works:

const regex = /<.*>.*<\/.*>/g

const regexString = (regex) => {
  return (s) => {
    return !s.match(regex)
  }
}

const validateString = regexString(regex)

const strings = [
  '<div>some text here',
  '<span>some text here',
  '<div>some text here</div>',
  '<h1>some text here</h1>',
]

const validated = strings.map(validateString)

console.log('Result:', validated)

Related