如何在字符串中出现第n个? [英] How to get the nth occurrence in a string?

查看:96
本文介绍了如何在字符串中出现第n个?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想得到第二次出现 ABC 的起始位置,如下所示:

I would like to get the starting position of the 2nd occurrence of ABC with something like this:

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

你会怎么做?

推荐答案

function getPosition(string, subString, index) {
   return string.split(subString, index).join(subString).length;
}

这篇关于如何在字符串中出现第n个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆