4

To test if a regex matches and assign it to a variable if it does, or assign it to some default value if it doesn't, I am currently doing the following:

var test = someString.match(/some_regex/gi);
var result = (test) ? test[0] : 'default_value';

I was wondering if there is any way to do the same thing in JS with one line of code.

Clarification: I am not trying to make my code smaller, but rather make it cleaner in places where I am defining a number of variables like so:

var foo = 'bar',
    foo2 = 'bar2',
    foo_regex = %I want just one line here to test and assign a regex evaluation result%
YemSalat
  • 19,986
  • 13
  • 44
  • 51

1 Answers1

8

You could use the OR operator (||):

var result = (someString.match(/some_regex/gi) || ['default_value'])[0];

This operator returns its first operand if that operand is truthy, else its second operand. So if someString.match(/some_regex/gi) is falsy (i.e. no match), it will use ['default_value'] instead.

This could get a little hacky though, if you want to extract the second capture group, for example. In that case, you can still do this cleanly while initializing multiple variables:

var foo = 'bar',
    foo2 = 'bar2',
    test = someString.match(/some_regex/gi),
    result = test ? test[0] : 'default_value';
tckmn
  • 57,719
  • 27
  • 114
  • 156
  • Exactly! Thanks a lot, I'm already using `||` to do similar things, but I never thought of putting the 'default value' into an array, that's a great tip! – YemSalat Jul 25 '14 at 04:55
  • 1
    @YemSalat Glad to help! I also added an alternate solution, since this could get a bit clunky if you want to grab capture groups or something. – tckmn Jul 25 '14 at 04:58
  • Although it looks a bit 'hacky' when I want to grab the group match out of the regex. `var result = (someString.match(/some_regex/gi) || [,'default_value'])[1]; // comma before the 'default value'` [Update] Yeah.. :) Thanks again! – YemSalat Jul 25 '14 at 04:58