[Fixed] How to slice only strings with digits at the end

Issue

I’m stuck in a problem. I have to slice the last two characters in a string, but only the strings that contain numbers.
I tried to use "nome": element.nome.slice(0,-2) and what I need is some kind of verification. But I can’t find out how!

Here is my code:

      this.aux3.forEach(element => {        
        this.novasColecoes.push({
          "produtos": element.produtos,
          "nome": element.nome.slice(0,-2),          
          "referencia": element.referencia,
          "selecionado": false          
        });        
      })

Solution

You can use regex.

const hasNumber = /\d/;

this.aux3.forEach(element => {        
    this.novasColecoes.push({
        "produtos": element.produtos,
        "nome": hasNumber.test(element.nome) ? element.nome.slice(0,-2) : element.nome,
        "referencia": element.referencia,
        "selecionado": false          
    });        
})

Leave a Reply

(*) Required, Your email will not be published