• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 267
  • Last Modified:

JavaScript: Test for same number of opening and closing tags

Using JavaScript, I want to test if a string contains the same number of opening and closing matching tags.

I use REGEX to gather the tags but I don't know how to count them for matches.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Demo</title>

<script type="text/javascript">
/*<![CDATA[*/

function checkTags(v) {
 // Count open tags of each time and count closed tags of each type and make sure the numbers match
 return(v.match(/(<+[^>]*?>)/g));
}
alert('Should return true:\n' + checkTags('<div><h1>Hello <strong>World</strong></h1></div>')); // Should return true because all open tags are closed
alert('Should return false:\n' + checkTags('<div><h1>Hello <strong>World</trsong></h1></div>')); // Should return false because not all open tags are correctly closed

/*]]>*/
</script>

</head>
<body>

<h1>I want to check and make sure that all open tags are closed.</h1>
<h2>The function should return true if all open tags are closed and false if not all open tags are closed.</h2>

</body>
</html>

Open in new window

0
hankknight
Asked:
hankknight
1 Solution
 
leakim971PluritechnicianCommented:
Check this :


function checkTags(v) {
 // Count open tags of each time and count closed tags of each type and make sure the numbers match
	 var m = v.match(/(<+[^>]*?>)/g);
	 var mA = [];
	 for(var i=0;i<m.length;i++) {
	 	if(typeof mA[m[i]] == "undefined") {
	 		mA[m[i]] = 1;
	 	}
	 	else {
	 		mA[m[i]] = parseInt(mA[m[i]]) + 1;
	 	}
	 }
	 for(tag in mA) {
	 	if( tag.indexOf("</")<0 ) {
		 	endtag = tag.replace("<","</");
	 		if( mA[tag] != mA[endtag] ) return false;
	 	}
	 }
	 return true;
}

Open in new window

0

Featured Post

Prep for the ITIL® Foundation Certification Exam

December’s Course of the Month is now available! Enroll to learn ITIL® Foundation best practices for delivering IT services effectively and efficiently.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now