-3

I am actually new to javascript and I'm trying to understand what went wrong with this code. I have a function that accepts a abc as a parameter.

This regular expression was given to me by one of my colleges. I don't have any idea what it's doing. Just wanted to understand what is the return statement here.

(function(abc) {
  var match = abc.match(/(\d+).+?(\d+)/);
  return +match[2] + 1;
});

I think the match will contain digits in decimal format but not clear about it. what will this return? Please let me understand this, will be a great help.

Wiktor Stribiżew
  • 484,719
  • 26
  • 302
  • 397
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match – str May 22 '19 at 11:14
  • 1
    The regex `match` method returns an array of results. `+match[2]` takes the 3rd array element from that array, coerces it to a number, and then adds 1. – Andy May 22 '19 at 11:19

2 Answers2

0
(\d+) - one or more digits (0-9)
.+?   - one or more periods (.)
(\d+) - one or more digits (0-9)

Regular expression visualization

Debuggex Demo

phuzi
  • 8,111
  • 3
  • 24
  • 43
0

You can easily create a snippet and debug it. Using provided example:

function getDiskInfo(diskinfo) {
  var match = diskinfo.match(/(\d+).+?(\d+)/);
  return +match[2] + 1;
}

console.log(getDiskInfo('111.222'));

In this example, as described by @phuzi:

var match = ['111.222', '111', '222'];

After that your return statement cast your element with index = 2 to Number and increments it by one. So using my example the final result will be 223.

adiga
  • 28,937
  • 7
  • 45
  • 66
dganenco
  • 1,403
  • 3
  • 16
  • [How do I create a runnable stack snippet?](https://meta.stackoverflow.com/questions/358992) – adiga May 22 '19 at 11:51