首页 > 解决方案 > 过滤器编号后跟数组中的点

问题描述

我想摆脱数组中后跟点的数字。

我尝试过这样的事情。

function parseMoves(){
  const pgnmoves = ["1.", "Nf3", "Nc6", "2.", "Bc4", "e6", "3."] // And so on.
  const reg = new RegExp('[0-9]+\.');  
  const filtered = pgnmoves.filter((x) => {
        return x != reg.test(x)
    })
  return filtered;
}

但这似乎不起作用,我对正则表达式不太擅长。

这是预期的输出:

["Nf3", "Nc6", "Bc4", "e6"]

谢谢你的帮助!

标签: javascriptarraysregexfilter

解决方案


你的正则表达式很好。您需要使用!运算符保留未通过测试的项目:

function parseMoves(){
  const reg = /[0-9]+\./; // /^[0-9]+\.$/ - if you want to remove just items that start with a number and have a single dot at the end 
  
  return pgnmoves.filter((x) => !reg.test(x));
}

const pgnmoves = ["1.", "Nf3", "Nc6", "2.", "Bc4", "e6", "3."]; // And so on.

const result = parseMoves(pgnmoves);

console.log(result);


推荐阅读