我正在编写一个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次.让我知道是否有更好的方法或替代方法来做同样的事情.如果我们只是给出事件(在运行时)来获取该字符的索引,那将是很好的.
以下是我的一些问题:
CQQ*_*QQL 21
function nth_occurrence (string, char, nth) {
var first_index = string.indexOf(char);
var length_up_to_first_index = first_index + 1;
if (nth == 1) {
return first_index;
} else {
var string_after_first_occurrence = string.slice(length_up_to_first_index);
var next_occurrence = nth_occurrence(string_after_first_occurrence, char, nth - 1);
if (next_occurrence === -1) {
return -1;
} else {
return length_up_to_first_index + next_occurrence;
}
}
}
// Returns 16. The index of the third 'c' character.
nth_occurrence('aaaaacabkhjecdddchjke', 'c', 3);
// Returns -1. There is no third 'c' character.
nth_occurrence('aaaaacabkhjecdddhjke', 'c', 3);
Run Code Online (Sandbox Code Playgroud)
Nel*_*son 12
你可以通过实现一个函数来轻松完成charAt(),如下所示:
function nth_ocurrence(str, needle, nth) {
for (i=0;i<str.length;i++) {
if (str.charAt(i) == needle) {
if (!--nth) {
return i;
}
}
}
return false;
}
alert( nth_ocurrence('aaaaacabkhjecdddchjke', 'c', 3) );//alerts 16
Run Code Online (Sandbox Code Playgroud)
感谢CQQL让我知道OP真正想要的是什么.我更新了一些我的原始函数来实现新的行为.
indexOf接受第二个参数,字符串中的字符索引开始搜索.
function nthChar(string, character, n){
var count= 0, i=0;
while(count<n && (i=string.indexOf(character,i)+1)){
count++;
}
if(count== n) return i-1;
return NaN;
}
var s= 'abcbbasdbgasdnnaabaasdert';
nthChar(s,'a',7);
Run Code Online (Sandbox Code Playgroud)