Advertisement
dimipan80

Count Number of DIVs

Nov 15th, 2014
225
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /* Write a JavaScript function countDivs(html) to count the number of all DIVs in given HTML fragment
  2.  passed as string. Write a JS program countOfDivs.js that invokes your function and prints the output
  3.  at the console. */
  4.  
  5. "use strict";
  6.  
  7. function countDivs(html) {
  8.     var pattern = /<div[^<]*>/g;
  9.     return html.match(pattern).length;
  10. }
  11.  
  12. console.log(countDivs(
  13.     '<!DOCTYPE html>' +
  14.     '<html>' +
  15.     '<head lang="en">' +
  16.     '<meta charset="UTF-8">' +
  17.     '<title>index</title>' +
  18.     '<script src="/yourScript.js" defer></script>' +
  19.     '</head>' +
  20.     '<body>' +
  21.     '<div id="outerDiv">' +
  22.     '<div class="first">' +
  23.     '<div><div>hello</div></div>' +
  24.     '</div>' +
  25.     '<div>hi<div></div></div>' +
  26.     '<div>I am a div</div>' +
  27.     '</div>' +
  28.     '</body>' +
  29.     '</html>'));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement