在javascript中查找字符串中字符的第n次出现

25 浏览
0 Comments

在javascript中查找字符串中字符的第n次出现

我正在编写一个JavaScript代码来查找字符串中字符的第n次出现。使用indexOf()函数,我们能够得到字符的第一次出现。现在的挑战是获取字符的第n次出现。我能够使用下面给出的代码来获取第二、第三次等等出现:

function myFunction() {
  var str = "abcdefabcddesadfasddsfsd.";
  var n = str.indexOf("d");
  document.write("First occurence " +n );
  var n1 = str.indexOf("d",parseInt(n+1));
  document.write("Second occurence " +n1 );
  var n2 = str.indexOf("d",parseInt(n1+1));
  document.write("Third occurence " +n2 );
  var n3 = str.indexOf("d",parseInt(n2+1));
  document.write("Fourth occurence " +n3);
  // and so on ...
}

结果如下所示:

First occurence 3 
Second occurence 9 
Third occurence 10 
Fourth occurence 14 
Fifth occurence 18 
Sixth occurence 19

我想将脚本泛化,以便能够找到字符的第n次出现,因为上面的代码要求我们重复脚本n次。如果我们只需在运行时提供出现次数,就能得到该字符的索引,那将非常好。

以下是我的一些问题:

  • 在JavaScript中如何实现这一点?
  • 是否有任何框架提供更简单的方法或其他框架/语言中实现相同功能的替代方法?
0