Reputation: 611
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
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
Upvotes: 0
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
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
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
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