0

i have certain string

const str = "・Welcome to ・StackOverFlow ・Best Regards";

i want to get all the indexes of the character "・"

unfornately the indexOf only gives the first instance

const str = "・Welcome to ・StackOverFlow ・Best Regards";
let bullet_ndx = [];
console.log(str.indexOf("・"));

is there a way i could find all the indexes of the certain character?

Stacks Queue
  • 848
  • 7
  • 18

2 Answers2

0

You can use a simple for loop, and an if condition for this.

const str = "・Welcome to ・StackOverFlow ・Best Regards";

let bulletIndex = []

for(var i = 0; i<str.length; i++){
  if(str[i] == "・"){
    bulletIndex.push(i)
  }
}

console.log(bulletIndex)
TechySharnav
  • 4,869
  • 2
  • 11
  • 29
  • i was hoping if there is one function to address this without looping but this is the best possible way. – Stacks Queue Aug 03 '21 at 03:53
  • @StacksQueue Unfortunately, there is not. There is `indexOf` and `lastIndexOf` that gives index of the char starting from forward and backwards respectively. You can write some user defined function though. – TechySharnav Aug 03 '21 at 03:57
0

indexOf takes a second argument, as a start position to look from

const str = "・Welcome to ・StackOverFlow ・Best Regards";
let bullet_ndx = [];
let index = 0;
while((index = str.indexOf("・", index))>=0) bullet_ndx.push(index++);
console.log(bullet_ndx);
Bravo
  • 6,022
  • 1
  • 10
  • 15