如何查找字符串中所有出现的字符。例如,字符串为:“ Hello world”
并且用户现在想要在存在“ L”的字符串的索引。在示例2,3和9中是哪个。如何在java-script / jquery中找到这样的索引?

最佳答案

您可以从this answer尝试以下代码:

function getIndicesOf(searchStr, str, caseSensitive) {
    var startIndex = 0, searchStrLen = searchStr.length;
    var index, indices = [];
    if (!caseSensitive) {
        str = str.toLowerCase();
        searchStr = searchStr.toLowerCase();
    }
    while ((index = str.indexOf(searchStr, startIndex)) > -1) {
        indices.push(index);
        startIndex = index + searchStrLen;
    }
    return indices;
}

09-07 16:19