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

JavaScript destructuring assignment after using regex

目前,我正在使用正则表达式重新排序一组 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;

看起来你想要

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 组内容