-2

i'm searching a simple way to find the index of one character / string between a list of characters.

Something which looks like

"3.14".indexOf([".",","])
"3,14".indexOf([".",","])

Both should return 1.

miorey
  • 828
  • 8
  • 19

2 Answers2

3

One way:

const testRegex = /\.|,/
const match = testRegex.exec("3.14");
console.log(match && match.index)

It uses a regular expression to search for either character, and uses the exec method on regular expressions which returns an object that has the index of the start of the match.

Andy Ray
  • 30,372
  • 14
  • 101
  • 138
2

You can loop through the array and return the first character's index whose index is not -1:

function getIndex(str, array){
  for(e of array){
    let index = str.indexOf(e);
    if(index != -1){
      return index;
    }
  }
}

console.log(getIndex("3.14", [".",","]))
console.log(getIndex("3,14", [".",","]))

You can also use Array.reduce:

function getIndex(str, array){
  return array.reduce((a,b) => a == -1 ? a = str.indexOf(b) : a, -1)
}

console.log(getIndex("3.14", [".",","]))
console.log(getIndex("3,14", [".",","]))
Spectric
  • 30,714
  • 6
  • 20
  • 43