最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin2浏览0评论

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';
发布评论

评论列表(0)

  1. 暂无评论