Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

273
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda