I’m trying to test whether the ending pattern in a string is an html closing tag (assuming trailing spaces are trimmed).
var str1 = "<em>I</em> am <strong>dummy</strong> <em>text.</em>"; //ends with html close tag
var str2 = "<em>I</em> am <strong>dummy</strong> <strong>text.</strong>"; //ends with html close tag
var str3 = "<em>I</em> am <strong>dummy</strong> text"; //does not end with html close tag
Using str1 above, I would like to get the position of the ending tag, which is an . Here are my attempts:
var rgx1 = /(<\/em>)$/g; // works. basic scenario. matches closing </em> tags at the end of the string.
var rgx2 = /<\s*\/\s*\w\s*.*?>/g; //matches html closing tags.
var rgx3 = /<\s*\/\s*\w\s*.*?>$/g; //doesn't work. supposed to match closing html tag at the end of the string
console.log(str.search(rgx1))
While rgx1 correctly returns the position of the ending tag, and rgx2 correctly returns the position of a closing html tag in general, I’m trying get a generalized regex that will return the positing of any html tag that ends the string. Why doesn’t rgx3 work?
Should just use a negative char class to match anything that’s not a closing >
var rgx = /<\/[^>]+>$/g;as to why rgx3 didn’t work… your pattern isn’t really good but it should technically match… if it didn’t work with the $ on the end there, then the string you are matching probably isn’t trimmed as you suppose it to be (or some other thing on the end other than closing html tag)