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


To check whether a regex matches and specifies it in a variable, or it has some default values If it does not, 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 this with a line of code in JS. Explanation: I am not trying to shorten my code but make it cleaner at such places where I am defining several types of variables:

  var foo = 'bar', foo2 = 'Bar2', foo_regex =% I want just one row here Reggae evaluation result%    

You can use the operator to test and assign ( || ):

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

This operator gives its first operator if that operand is true, and its second operator is someString.match (/ some_regex / gi) Falsei (i.e. Mail), instead of using ['default_value'] .

However, if you want to remove the second capture group, for example, it might get a little bit. In that case, you can do this properly even when you start multiple variables:

  var foo = 'bar', foo2 = 'bar2', test = someString.match (/ some_regex / Gi), results = test? Test [0]: 'default_value';    

Comments

Popular posts from this blog

ios - Adding an SKSpriteNode to SKScene from a child SKSpriteNode -

Matlab transpose a table vector -

c# - Textbox not clickable but editable -