Tuesday, May 28, 2024
 Popular · Latest · Hot · Upcoming
178
rated 0 times [  183] [ 5]  / answers: 1 / hits: 14922  / 11 Years ago, thu, january 16, 2014, 12:00:00

I want to come up with Regular Expression to return true if the a closed html tag is matched with an open one in specific text that gets passed in JavaScript. If there is an unmatched tag, it should return false;



For example, if the following text is passed <div>Test</div> it should return true
but if the following text gets passed <div>Test</div><div>Boom it should return false



I can only get it to match the first div tags to return true with the following expression



    var text = <div>Test</div>; 
var text2 = <div>Test</div><div>;
var regex = /[^<>]*<(w+)(?:(?:s+w+(?:s*=s*(?:.*?|'.*?'|[^'>s]+))?)+s*|s*)>[^<>]*</1+s*>[^<>]*|[^<>]*<w+(?:(?:s+w+(?:s*=s*(?:.*?|'.*?'|[^'>s]+))?)+s*|s*)/>[^<>]*|<!--.*?-->|^[^<>]+$/;
var match = regex.test(text);
console.log(match); // true
var match = regex.test(text2);
console.log(match2); // still true should be false


How can I fix it so it functions the way I want it to.


More From » regex

 Answers
9

The test method returns true for match2 because it has found a match.



In order to fix it, change your regex this way:



^(?:<(w+)(?:(?:s+w+(?:s*=s*(?:.*?|'.*?'|[^'>s]+))?)+s*|s*)>[^<>]*</1+s*>|<w+(?:(?:s+w+(?:s*=s*(?:.*?|'.*?'|[^'>s]+))?)+s*|s*)/>|<!--.*?-->|[^<>]+)*$


Description (click to enlarge)




Regular



Demo



http://jsfiddle.net/r2LsN/



Discussion



The regex defines all the allowed patterns firstly:




  1. Tags with body: <tag>...</tag>

  2. Tags without body: <tag/> (here we can find zero or more spaced before /)

  3. Comments <!-- ... -->

  4. Any text that is not < or >.



then these patterns can appear zero or more times between the beginning and the end of the tested string: ^(?:pattern1|pattern2|pattern3|pattern4)*$.


[#48649] Wednesday, January 15, 2014, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
deanna

Total Points: 84
Total Questions: 86
Total Answers: 107

Location: Cyprus
Member since Wed, Dec 8, 2021
3 Years ago
;