如何仅对末尾带有数字的字符串进行切片

How to slice only strings with digits at the end

我遇到了问题。我必须对字符串中的最后两个字符进行切片,但只对包含数字的字符串进行切片。 我尝试使用 "nome": element.nome.slice(0,-2) 我需要的是某种验证。但是我不知道怎么办!

这是我的代码:

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

是这样的吗?

// new function
 function isNumber(val) {
   return !isNaN(val);
  }

// You foreach

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

您可以使用正则表达式。

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

我会提出以下单行解决方案:

element.nome.split('').some(b => b.match(/\d/)) ? element.nome.slice(0,-2) : element.nome

首先使用split分割字符串,这意味着我们得到一个字符数组:

"test123".Split('');
// becomes
let splitString = ['t','e','s','t','1','2','3'];

然后我们可以在新数组上使用“some”数组函数。如果某些(任何)条件为真,则此 return 为真布尔值。

在我们的条件下,我们使用正则表达式 (RegExp)。 "/\d/" 此 RegExp 评估为“包含一个数字”。这就是我们过滤数字的方式。

// "match" returns true for 1, 2 and 3, so "some" returns true
var containsDigit = splitString.some(s => s.match(/\d/))

然后我们使用三元运算符,如果条件为真,我们return“element.nome.slice(0,-2)”否则我们return未修改的“element.nome"

{nome: containsDigit ? true : false}

应用于您的示例:

this.aux3.forEach(element => {        
        this.novasColecoes.push({
          "produtos": element.produtos,
          "nome": element.nome.split('').some(n => n.match(/\d/)) ? element.nome.slice(0,-2) : element.nome,          
          "referencia": element.referencia,
          "selecionado": false          
        });        
      })