使用正则表达式后的JavaScript解构赋值

时间:2016-11-18 12:38:53

标签: javascript arrays regex destructuring

目前,我正在使用正则表达式对Set 1 Total Games Over/Under 9.5的设置字符串进行重新排序,以使其显示为Under/Over N Giochi Set 1。目前我使用以下内容输出数据:

let marketLabel = 'Set 1 Total Games Over/Under 9.5';
match = regexUnderOver.exec(marketLabel);
browserReturn = match[3] + '/' + match[2] + ' ' + match[4] + ' Giochi Set ' + match[1];

但是,在将数据分配给browserReturn变量之前,我更倾向于使用解构赋值来正确排序数据。我试图遵循MDN上的约定,但对我来说没有意义。如果你能用我发布的例子告诉我,我将不胜感激。完整代码如下:

let marketLabel = 'Set 1 Total Games Over/Under 9.5';
const regexUnderOver = /^Set ([0-9.]+) Total Games (Over)\/(Under) ([0-9.]+)$/;
match = regexUnderOver.exec(marketLabel);
browserReturn = match[3] + '/' + match[2] + ' ' + match[4] + ' Giochi Set ' + match[1];
return browserReturn;

1 个答案:

答案 0 :(得分:2)

看起来你想要

let marketLabel = 'Set 1 Total Games Over/Under 9.5';
const regexUnderOver = /^Set ([0-9.]+) Total Games (Over)\/(Under) ([0-9.]+)$/;
let [fullmatch, firstNum, over, under, lastNum] = regexUnderOver.exec(marketLabel);
let browserReturn = `${under}/${over} ${lastNum} Giochi Set ${firstNum}`;
console.log(browserReturn);

感兴趣[fullmatch, firstNum, over, under, lastNum] = regexUnderOver.exec(marketLabel)

  • fullmatch - 整场比赛
  • firstNum - 捕获第1组内容
  • over - 捕获第2组内容
  • under - 捕获第3组内容
  • lastNum - 捕获第4组内容