【问题标题】:Javascript: test regex and assign to variable if it matches in one lineJavascript:测试正则表达式并分配给变量,如果它在一行中匹配
【发布时间】:2014-09-16 20:50:46
【问题描述】:

测试正则表达式是否匹配,如果匹配则将其分配给变量,如果不匹配,则将其分配给某个默认值, 我目前正在执行以下操作:

var test = someString.match(/some_regex/gi);
var result = (test) ? test[0] : 'default_value';

我想知道是否有任何方法可以用一行代码在 JS 中做同样的事情。

澄清: 我并不是要让我的代码更小,而是在我定义许多变量的地方让它更干净,如下所示:

var foo = 'bar',
    foo2 = 'bar2',
    foo_regex = %I want just one line here to test and assign a regex evaluation result%

【问题讨论】:

    标签: javascript regex var assign code-structure


    【解决方案1】:

    您可以使用 OR 运算符 (||):

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

    如果该操作数为真,则此运算符返回其第一个操作数,否则返回其第二个操作数。因此,如果 someString.match(/some_regex/gi) 是假的(即不匹配),它将使用 ['default_value'] 代替。

    但是,例如,如果您想提取第二个捕获组,这可能会有些麻烦。在这种情况下,您仍然可以在初始化多个变量时干净利落地执行此操作:

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

    【讨论】:

    • 没错!非常感谢,我已经在使用|| 做类似的事情,但我从来没有想过将“默认值”放入数组中,这是一个很棒的提示!
    • @YemSalat 很高兴为您提供帮助!我还添加了一个替代解决方案,因为如果你想抓取捕获组或其他东西,这可能会有点笨拙。
    • 虽然当我想从正则表达式中获取分组匹配时它看起来有点“hacky”。 var result = (someString.match(/some_regex/gi) || [,'default_value'])[1]; // comma before the 'default value' [更新] 是的.. :) 再次感谢!
    猜你喜欢
    • 1970-01-01
    • 2013-01-20
    • 2014-07-20
    • 1970-01-01
    • 2010-11-17
    • 2015-07-06
    • 1970-01-01
    • 1970-01-01
    • 2011-06-12
    相关资源
    最近更新 更多