【问题标题】:How to use match() in if else condition correctly. (node.js)如何在 if else 条件下正确使用 match()。 (node.js)
【发布时间】:2021-09-30 08:30:27
【问题描述】:

我有动态响应数据,要么是完全随机的字符串,要么是像 Johnny likes to eat {food} for breakfast 这样的字符串,因为我正在尝试匹配。

var data = response.body
if (data.match(/Johnny likes to eat(.*)for breakfast/)[0]) {
  console.log("Johnny in fact likes to eat" + data.match(/Johnny likes to eat(.*)for breakfast/)[1])
} else {
  console.log("Johnny eats nothing") //this doesnt get executed, just logs null
}

如果语句为假,它只会记录null,而不是else。我怎样才能做到这一点?

【问题讨论】:

  • “约翰尼喜欢在早餐时吃 {food}”总是这个结构吗?

标签: javascript node.js if-statement dynamic match


【解决方案1】:

试试这个:

const data = "Johnny likes to eat apples for breakfast"

const string = data.split(" ")[4] // Gets the fifth string 
if (string != "for")
  console.log("Johnny in fact likes to eat " + string)
else
  console.log("Johnny eats nothing")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-21
    • 1970-01-01
    • 2019-04-25
    • 2021-09-19
    • 2021-12-21
    • 2021-08-07
    • 1970-01-01
    相关资源
    最近更新 更多