Skip to content

Instantly share code, notes, and snippets.

@jasp402
Created June 6, 2020 14:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jasp402/70c1a30e3f382480746fb4488c7cb548 to your computer and use it in GitHub Desktop.
Save jasp402/70c1a30e3f382480746fb4488c7cb548 to your computer and use it in GitHub Desktop.
JavaScript - Get the index of each word that matches the search.
const getAllIndexText = (str, letter, caseSensitive = false) => {
//all lowercase letters
if (caseSensitive) {
str = str.toLowerCase();
letter = letter.toLowerCase();
}
let arPosition = [];
while (str.indexOf(letter) > -1) {
arPosition.push(str.indexOf(letter));
str = str.replace(letter, '__');
}
return arPosition;
};
let arIndex = getAllIndexText("Un tete a tete con Tete", "te", true);
console.log(arIndex); //[ 3, 5, 10, 12, 19, 21 ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment