Search code examples
javascriptregexvarassigncode-structure

Javascript: test regex and assign to variable if it matches in one line


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%

Solution

  • 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';