如何在javascript中找到所有字符串出现的索引? [英] How to find the index of all the occurrences of string in javascript?

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

问题描述

使用indexOf函数我们可以找到特定字符串的索引。如何获取string的所有出现的索引。有没有最简单的方法呢?

Using indexOf function we can find the index of particular string. How to get the index of all the occurrences of string.Is there any simplest way to do it?

推荐答案

Tty

Tty
string myString= "Check occurrences within this string.";
int count = myString.match(/in/g);// Search for 'in' occurrences in string


使用正则表达式:

Use a regex:
var regex = /,/g;
var instr = "1,2,3,4";
var current;
var matchIndexes = [];

while ((current = regex.exec(instr)) != null)
{
   matchIndexes.push(current.index);
}


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

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