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

To test if a regex matches and assign it to a variable if it does, or assign it to some default value i

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%

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%
Share Improve this question asked Jul 25, 2014 at 4:49 YemSalatYemSalat 21.6k13 gold badges48 silver badges51 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 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';

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745303752a4621591.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信