简体   繁体   中英

How to use match() in if else condition correctly. (node.js)

I have dynamic response data that either has a completely random string, or a string like Johnny likes to eat {food} for breakfast data as I'm trying to match.

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
}

If the statement is false, it would just log null and not to the else . How can I make it that it would?

Try this:

 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")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM