1

I have the following code in javascript.

    var contents = '<p>this is some text.<span class="Am"></span>This is som text<span class="Am"></span>This is some text<span class="Am"></span></p>';

Now I have to find the number of occurences of span tag inside this string and then use a loop throgh this number. For example

 function doStuff(){
        var contents = '<p>this is some text.<span class="Am"></span>This is som text<span class="Am"></span>This is some text<span class="Am"></span></p>';
        var spans = 'Number of spans in the string';  // this is required to me
        for(i=1;i<=spans;i++){
            // do some stuff
            }
       }

Can anyone tell me how it can be done with javascript ?

Thanks in advance.

user2826169
  • 285
  • 3
  • 7
  • 16

4 Answers4

3

One way:

var temp = document.createElement("DIV");
temp.innerHTML = contents;

var count = temp.getElementsByTagName("SPAN").length;
Alex K.
  • 171,639
  • 30
  • 264
  • 288
2

try this, its pretty hardcode but works:

contents.split("</span>").length - 1

you can also try this:

contents.match(/<span/ig).length
Mehran Hatami
  • 12,723
  • 6
  • 28
  • 35
1

dam, folks are quick at answering : ) ...

Here is a reusable way to throw in the mix

    /* function stringmatchCount(str,instr) {
       var count = instr.match(/str/g);
       return count.length;
     } */ 

*UPDATE AS ROKO better shows

  function stringmatchCount(str,dlm) {
       var d = new RegExp(dlm, "g");
        return str.match(d).length;
     }

usage, like in your example.

 function doStuff(){
   var contents = '<p><span class="Am"></span>doo, daaa<span></span>';
   var spans = stringmatchCount(contents,'<span');
    for (var i = 0, len=spans; i < len; ++i) {
     ... 
     }
  }
Rob Sedgwick
  • 5,216
  • 4
  • 20
  • 36
0

Try this code :-

contents.match(/\<span\>//g).length