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

标签 javascript

我正在编写一个 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 中做到这一点?
  • 是否有框架提供任何功能以更简单的方式执行相同的实现,或者在其他框架/语言中实现相同的替代方法有哪些?

最佳答案

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);

关于javascript - 在javascript中查找字符串中某个字符的第n次出现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12744995/

相关文章:

javascript - 为什么 JavaScript 中 (1 < NaN) 为假?

JavaScript - 下拉菜单不起作用

javascript - 将节点动态添加到 D3 树布局请求(切换时)

javascript - 更改元素内容

javascript - Electron Js - 主进程发生javascript错误

javascript - JS 游戏使用 CSS 而不是 JS 将响应式高度和宽度设置为 Canvas

javascript - Angular Directive(指令)绑定(bind)

javascript - 如何使工具提示在 mouseenter 上保持可见?

javascript - 将多个输入值作为不同行插入不同表中

javascript - 如何使用 jQuery/JavaScript 检测 ios 设备并仅隐藏 iPhone 和 iPad 的 Bootstrap 模式?