0

I have been going through nodeschool's regex-adventure and I have just completed the captures lesson.

My solution:

module.exports = function (str) {
    var x = /x=(\d+)/.exec(str);
    return x && x[1];
}

However the reference solution has

module.exports = function (str) {
    var x = /x=(\d+)/.exec(str);
    return x ? x[1] : null;
}

I am really just curious as to what the last line means. x zero or one time x[1] but I am unaware of what : null; means in this instance. Does it mean "if not null"?

Michael Gaskill
  • 7,913
  • 10
  • 38
  • 43

2 Answers2

1

It's ternary operator:

(condition ? expressionIfConditionIsTrue : expressionIfConditionIsFalse)

It's a shortcut for

if (expression) {
    // expressionIfConditionIsTrue   
} else {
    // expressionIfConditionIsFalse   
}

So if the regex founds a match then x[1] is returned and otherwise, the function returns null.

MartyIX
  • 27,828
  • 29
  • 136
  • 207
1

Did you hear about ternary operator?

syntax:

condition ? true : false

So here,

return x ? x[1] : null;

If there is a match, it should return the characters which are fetched by the group index 1 else it should return null.

Avinash Raj
  • 172,303
  • 28
  • 230
  • 274