我想获得的起始位置2nd发生ABC像这样的东西:
var string = "XYZ 123 ABC 456 ABC 789 ABC";
getPosition(string, 'ABC', 2) // --> 16
Run Code Online (Sandbox Code Playgroud)
你会怎么做?
我正在编写一个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 ×2