Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

277
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda