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

272
Views
How to replace tokens in a classList incrementally?

I'd like to find a way to replace the token 'c1' with 'c2', replace 'c2' with 'c3', etc. using fewer lines of code.

Currently, I'm going through each element with forEach, like so:

carsLeft.forEach(carLeft => moveCarLeft(carLeft))

And then to move the element one space over to the left, I enter into a switch statement to reassign a class to it:

switch(true) {
        case carLeft.classList.contains('c1'):
            carLeft.classList.replace('c1', 'c2')
            break
        case carLeft.classList.contains('c2'):
            carLeft.classList.replace('c2', 'c3')
            break
        case carLeft.classList.contains('c3'):
            carLeft.classList.replace('c3', 'c4')
            break
    }

I was wondering if there is a way to use regular expressions to simplify the switch statement into something like this:

carLeft.classList.replace(`c\d`, `c\d+`)

...or perhaps another way aside from using regular expressions. Thank you for taking the time to read this. Any help would be much appreciated.

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

0

You could use a for loop:

for (let i = 1; i <= 3; i++) {
    if (carLeft.classList.contains("c"+i)) {
        carLeft.classList.replace("c"+i, "c"+(i+1));
        break;
    }
}
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!