记录一个字符串中有多少个i

 //记录一个字符串中有多少个i

  var text = "ksdjdiiiiifdjiilkdfkdjfidifjd";

  var pattern1 = /i/g;

  var matches = new Array();

  var count = 0;

  matches = pattern1.exec(text);

  var result = pattern1.test(text);

  if(result){

       count+=1;

while(pattern1.lastIndex>0){

  matches = pattern1.exec(text);

  count++;

  };

  }

        console.log("共有i的个数是:"+count);

//还有一种可以用indexOf方法

var postions = new Array();

var pos = text.indexOf("i");

while(pos>-1){

postions.push(pos);

pos = text.indexOf("i",pos+1);

}

console.log("利用indexOf "+postions.length);

猜你喜欢

转载自577439237.iteye.com/blog/2340132
今日推荐