相关疑难解决方法(0)

如何在字符串中出现第n个?

我想获得的起始位置2nd发生ABC像这样的东西:

var string = "XYZ 123 ABC 456 ABC 789 ABC";
getPosition(string, 'ABC', 2) // --> 16
Run Code Online (Sandbox Code Playgroud)

你会怎么做?

javascript

92
推荐指数
3
解决办法
8万
查看次数

在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 ...
}
Run Code Online (Sandbox Code Playgroud)

结果如下

First occurence 3 
Second occurence 9 
Third occurence 10 
Fourth occurence 14 
Fifth occurence 18 
Sixth occurence 19
Run Code Online (Sandbox Code Playgroud)

我想概括脚本,以便我能够找到第n次出现的字符,因为上面的代码要求我们重复脚本n次.让我知道是否有更好的方法或替代方法来做同样的事情.如果我们只是给出事件(在运行时)来获取该字符的索引,那将是很好的.

以下是我的一些问题:

  • 我们如何在JavaScript中完成它?
  • 是否有任何框架提供任何功能以更简单的方式执行相同的实现,或者在其他框架/语言中实现相同的替代方法是什么?

javascript

22
推荐指数
3
解决办法
3万
查看次数

标签 统计

javascript ×2