-1

I'm looking for a way to know all the positions of a certain part of a string, so for example, if I have a let variable = "test" and I want to know the location of all the "t"s.

I tried using indexOf(), but it does only return the location of the first "t" and stops afterwards.

Is there a way to do this with all "t"s?

Flo
  • 29
  • 3

2 Answers2

1

let x = "test"
let y = []
for (let i = 0; i < x.length; i++){
   if (x[i] == "t") y.push(i)
}
console.log(y)
DCR
  • 14,737
  • 12
  • 52
  • 115
  • 3
    This is virtually identical to [this answer](https://stackoverflow.com/a/10710400/6243352), but without all of the detail and benchmark. Why not mark a dupe instead of reinventing the wheel? – ggorlen Apr 09 '22 at 20:43
0

let variable = "test";
for (let i = 0; i < variable.length; i++){
    if (variable[i] === 't'){
        console.log(i);
    }
}
roii31
  • 33
  • 4