Search code examples
javascriptclassreplacetokencontains

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.


Solution

  • 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;
        }
    }