1

How to find all occurrences of a character in a string. For example string is: "Hello world" and user want to now the indexes of string where 'L' is present. Which is in example 2,3 and 9. How to find indexes like this in java-script/jquery ?

mshahbazm
  • 611
  • 1
  • 11
  • 23
  • I know how to find first occurrence, but failed to figure out how to find all occurrences of a character. – mshahbazm Nov 27 '12 at 17:18
  • Using loop number of occurrences could be found but i do not know to return all of that indexes. – mshahbazm Nov 27 '12 at 17:20
  • Possible duplicate of [How to find all occurrences of one string in another in JavaScript?](http://stackoverflow.com/questions/3410464/how-to-find-all-occurrences-of-one-string-in-another-in-javascript) – user Nov 09 '15 at 03:08

5 Answers5

1

For example, if you wanted to find all b's and then write them to the document -

var foo = "foo bar baz bat";

var pos = foo.indexOf("b");
while(pos > -1) {
    document.write(pos + "<br />");
    pos = foo.indexOf("b", pos+1);
}

Output:

4
8
12
dsgriffin
  • 66,495
  • 17
  • 137
  • 137
1

Here is some pseudocode. This is how you should try and work out the logic for problems before you try to start coding.

var indeces = {};

for(each character in string)
   if(character == characterImLookingFor)
       indeces.add(currentIndex);

return indeces;
thatidiotguy
  • 8,701
  • 13
  • 60
  • 105
1

You can try something like the following code, from 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;
}
Community
  • 1
  • 1
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
1
function getIndexes(str,char) {
    var index = str.indexOf(char);
    var indexes = [];

    while(index != -1) {
        indexes.push(index);
        index = str.indexOf(char,index+1);
    }

    return indexes;
}

Usage:

getIndexes("Hello world","l"); // returns [2,3,9]
lostsource
  • 21,070
  • 8
  • 66
  • 88
0

You can also use regular expressions to achieve this:

var str = "Give me indexes of i in this string";
var regex = /i/gi, result;
while ((result = regex.exec(str)) ) {
    console.log(result.index);
}

//Output: 1, 8, 19, 21, 26, 32

DEMO

Sergiu Dumitriu
  • 11,455
  • 3
  • 39
  • 62
Gurpreet Singh
  • 20,907
  • 5
  • 44
  • 60