mshahbazm
mshahbazm

Reputation: 611

Find the indexs of all occerences a character in a string

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 ?

Upvotes: 1

Views: 278

Answers (5)

Gurpreet Singh
Gurpreet Singh

Reputation: 21233

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

Upvotes: 0

Rahul Tripathi
Rahul Tripathi

Reputation: 172398

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;
}

Upvotes: 1

lostsource
lostsource

Reputation: 21830

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]

Upvotes: 1

thatidiotguy
thatidiotguy

Reputation: 8981

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;

Upvotes: 1

dsgriffin
dsgriffin

Reputation: 68576

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

Upvotes: 1

Related Questions