【问题标题】:Javascript to return "false" if no regex matches如果没有正则表达式匹配,Javascript 将返回“false”
【发布时间】:2018-03-18 17:54:56
【问题描述】:

以下代码 examines the content of inputData.body for a 32-character string match,并且 - 据我所知 - 将所有匹配项放在一个数组中。

// stores an array of any length (0 or more) with the matches
var matches = inputData.body.match(/\b[\w-]{32}\b/g)

// the .map function executes the nameless inner function once for each element of the array and returns a new array with the results
return matches.map(function (m) { return {str: m} })

我现在需要代码在没有匹配表达式的情况下返回 something,例如。字符串"false"

我无法让这个补充工作......

// stores an array of any length (0 or more) with the matches
var matches = inputData.body.match(/\b[\w-]{32}\b/g)

if (matches == null){
    return 'false'
}

// the .map function executes the nameless inner function once for each element of the array and returns a new array with the results
return matches.map(function (m) { return {str: m} })

如果出现空虚,我应该如何有条件地返回一些东西?

【问题讨论】:

  • 代码是否封装在函数中?
  • 我认为你的代码应该可以工作。
  • 你确定调用者准备好获取一个字符串作为函数的结果吗?它可能需要一个数组。
  • 也许你应该在没有匹配的时候返回一个空数组。
  • 你的意思是你不能让它工作?它做了什么而不是返回字符串'false'

标签: javascript arrays is-empty


【解决方案1】:

调用者需要一个对象数组或单个对象(可能被视为该对象的数组)。所以返回一个对象。

if (matches == null) {
    return { str: "false"; }
}
return matches.map(function (m) { return {str: m} });

或在单个语句中:

return matches == null ? { str: "false"; } : matches.map(function (m) { return {str: m} });

【讨论】:

  • 注意以上所有。我需要一些肯定的输出,而不是填补空的任何东西。在上面用false 填充str 的地方似乎可以做到这一点,并让我能够在后续步骤中测试单词false。我知道那不漂亮,但我需要。不过,我想我需要对此进行条件化.. ? if (matches == null){ return {str: 'false'}; } else { return matches.map(function (m) { return {str: m} }) } ?
  • 如果if 执行return,则不需要else
  • 我查看了文档,似乎说空数组是可以的。 如果 Zapier 的 Code 是 Zap 的触发器并且返回一个空数组,则什么都不会发生。
  • 如果 Zapier 的 Code 是 Zap 的触发器,并且您返回一个空数组 [],我们将不会触发任何下游操作 - 就好像您在代码中说“没关系”。
  • 在没有找到匹配的正则表达式的情况下,zap 的代码操作在任务历史记录中抛出“此代码步骤遇到错误”。支持人员说:“现在我们没有很好的方法来解决这个问题,因为错误消息向我们表明出了问题。如果没有任何问题,您可以更改代码以输出诸如“否”或“假”之类的东西找到。那样它每次都会成功,然后你的过滤器可以是“不包含你选择的任何单词”。我知道它并不完美 [...] 但这是一种确保我们不在该步骤中出现错误。”
【解决方案2】:

调用者可能期望一个数组,如果没有匹配,它应该是一个空的。您不需要if 语句,只需这样做:

return (matches || []).map(function (m) { return {str: m} })

【讨论】:

    【解决方案3】:

    要测试正则表达式是否匹配特定模式,您应该使用返回 true/false 的 test() 方法。

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-26
      • 1970-01-01
      • 2015-09-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多