What is the value of \ 1 in the regular expression in javascript?

6

I was taking a look at this response from @Sergio here on the stackoverlow:

link

There was a snippet of code like this:

/^(\d)+$/.test(111)

What exactly does do in this regular expression?

    
asked by Wallace Maxters 22.10.2015 в 21:54

2 answers

7

If you have one or more capture groups in the regex this will fetch the value captured in the first group. As that a variable that assumes the value of the group. If there is more than one you can use , etc.

For example:

  • /^(\w)(\d)$/

accepts strings with two equal letters followed by two equal numbers two to two. For example aa11 or bb33 ( example ).

  • /^(\w)(\d)$/

looks like the above example but accepts merged patterns. For example a1a1 or b3b3 ( example ).

    
22.10.2015 / 21:58
3

It is the result of the first group that is represented by ( ) , so bar number ( ) get the value of it. Other languages use dollar sign, ex: $1 .

Regular expressions have daytime utilities, say you have a text file full of inserts where dates are in dd/mm/yyyy format with a suitable editor you can convert to yyyy-mm-dd with replace.

10/23/2015

Use ([0-9]{2})\/([0-9]{2})/([0-9]{4}) to caputrar the date and This will change the position of the year for the day, then it is only to change the separator from \ to - and date will be 2015-10-23. / p>     

22.10.2015 в 21:57