The best way to find the starting index of each occurrence of a duplicate
word in a string with javaScript
findIndexes(s,kw) is supposed to find the starting index of each
occurrence of a keyword(kw) in a string(s).
function findIndexes(s,kw){
var result = [];
s = " " + s.toLowerCase() + " ";
kw = " " + kw.toLowerCase() + " ";
var i = s.indexOf(kw);
while (i >= 0){
result.push(i);
i = s.indexOf(kw, i+kw.length);
};
console.log("The index of " + kw +":");
for (var i =0; i < result.length; i++)
console.log(result[i]);
}
findIndexes("Apple PEAR banana pineapple STRAWBERRY appLE CrabApple
ApPle","apple");//return 0, 39, 55
This is the best I could get it working but I don't like that I have to
put space before and after both string set(s = " " + s.toLowerCase() + "
"; kw = " " + kw.toLowerCase() + " ";) to exclude those words contain the
search word (pineapple,ect...).I tried to use RegExp(kw = new RegExp('\b'
+ kw + '\b');) but then it is not working. I would appreciate if you can
come up with a better solution. Thanks!
No comments:
Post a Comment