Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

164
Views
How can I found the index of a array of characters in a string without looping on the array characters

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.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report

0

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", [".",","]))

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!