How can I found the index of a array of characters in a string without looping on the array characters [duplicate]
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.
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", [".",","]))