Understanding regex

i am new to coding and was trying to write a function that counts the number potato patterns in a string, so i found this code that uses regex, given that i know nothing about regex. Code is working fine.

const string  =  "bEpotatoEpotatoFGBuFBpotatoRrHgUpotatoHlNpotatoFYaYr"
const count = (str) => {

  const re = /potato/g

  return ((str || '').match(re) || []).length



so this is what i understood
–we created a function count that takes str as a parameter.
–then we saved the patterns inside re.
now what the hell is this third line that starts with return, can anyone please put it into words so that i know what it means??? i know what return is but what’s after that ???

str || ''
Take str variable or if it’s falsy (empty, undefined etc.) take an empty string.

Call match method on it with regular expression re.

|| []
match will return either an array with matches or null if no matches found. If it’s null, default to an empty array.

Count the matches.

1 Like

Hey @aamirasr.2062!

FCC has a section on regex that you can go through.

There is also an handy tool online called regex 101. You can put your regular expressions in there and it gives detailed explanations on what the code is doing. It kind of acts like a debugger for regex.

1 Like

so basically we have used regex in this line only
const re = /potato/g
rest all are just standard JS statements ???

thanks a ton. this link is amazing. :slight_smile:

Yes. It’s just regular JS.

1 Like