筛选号后点出一个数组。

问题描述 投票:0回答:1

我想去掉数组中数字后面的点。

我试过这样的方法。

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"]

谢谢你的帮助!

javascript arrays regex filter
1个回答
1
投票

你的正则表达式很好。你需要保留那些没有通过测试的项目,通过使用 ! 操作符。

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

0
投票

你的regex没有工作,因为 '\.' 不是有效的字符串转义序列,并且你的模式匹配1个或多个数字,然后是除换行符以外的任何字符,等于 [0-9]+.. 你也可以在字符串中的任何地方匹配这种模式,而你的数据意味着你只需要过滤出 number. 如弦。

还有。x != reg.test(x) 意味着你将数组中的每一个字符串与以下任何一个进行比较 truefalse的结果,你必须返回从 reg.test(x)filter 方法。您需要 .filter((x) => !reg.test(x)).

为了进一步筛选出匹配的数字,您可以使用

/^\d+\.$/

Regex详情

  • ^ - 弦首
  • \d+ - 1个或多个数字
  • \. - 点子
  • $ - 句号

请看JS的演示。

const pgnmoves = ["1.", "Nf3", "Nc6", "2.", "Bc4", "e6", "3."];
const reg = /^\d+\.$/;
const parseMoves = (vals, reg) => vals.filter((x) => !reg.test(x))
const filtered = parseMoves(pgnmoves, reg);
console.log(filtered)

0
投票

你可以试试这个。

function parseMoves(){
 const pgnmoves = ["1.", "Nf3", "Nc6", "2.", "Bc4", "e6", "3."]
 const reg = new RegExp(/.*(\d\.)$/);  
 const filtered = pgnmoves.filter((x) => {
    return reg.test(x)==false;
 })
 return filtered;
}
© www.soinside.com 2019 - 2024. All rights reserved.