返回指定字符串所有位置的字符串方法吗? [英] A string method to return all placements of a specified string?

查看:151
本文介绍了返回指定字符串所有位置的字符串方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否存在像indexOf这样的方法,但是该方法将在数组中返回指定字符串的所有位置?就像"test test atest".method(test)会返回[0, 5, 11]

Is there a method like indexOf but that would return all placements of the specified string, in an array? Like "test test atest".method(test) would return [0, 5, 11]

推荐答案

我不知道这种方法,但是使用indexOf编写起来很容易:

I'm not aware of such a method, but it's pretty easy to write using indexOf:

function findAll(string, substring) {
    var i = -1;
    var indices = [];

    while ((i = string.indexOf(substring, i+1)) !== -1) {
        indices.push(i);
    }

    return indices;
}

console.log(findAll("test test atest", "test"));

// Output:
// [ 0, 5, 11 ]

这篇关于返回指定字符串所有位置的字符串方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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