admin管理员组文章数量:1419201
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
1 Answer
Reset to default 8You 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';
本文标签: Javascript test regex and assign to variable if it matches in one lineStack Overflow
版权声明:本文标题:Javascript: test regex and assign to variable if it matches in one line - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745303752a2652526.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论