简体   繁体   English

如何在javascript中的字符串中查找子字符串的出现次数?

[英]how to find the number of occurences of a substring in a string in javascript?

I have the following code in javascript. 我在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. 现在,我必须找到此字符串内span标签的出现次数,然后使用循环遍历此数字。 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 ? 谁能告诉我如何使用javascript来完成?

Thanks in advance. 提前致谢。

One way: 单程:

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

var count = temp.getElementsByTagName("SPAN").length;

try this, its pretty hardcode but works: 试试看,它的代码很硬,但是可以工作:

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

you can also try this: 您也可以尝试以下方法:

contents.match(/<span/ig).length

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 *更新为ROKO更好地显示

  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) {
     ... 
     }
  }

试试这个代码:-

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM