regex: javascript global flag

2020-09-29

 | 

~2 min read

 | 

235 words

Recently I wrote about my regular expression prowess with figuring out a pattern to match on markdown links.

When I went to implement it, however, I ran head first into a wall and ate some humble pie.

function parseTitle(rowTitle) {
  const pattern = /!?\[([^\]]*)\]\(([^\)]+)\)/gm
  const groups = rowTitle.match(pattern)
  return groups
}

const title = `[test](google.com)`
console.log(parseTitle(title)) // ["[test](google.com)"]

The images I was looking at seemed like they’d work, but I was only getting one match back when I actually tried it in my scripts.

In the test environment, all of my matches were being highlighted.

multi groups

The issue was that I was so focused on seeing that all of the lines matched that I missed how the global flag works in Javascript!

Specifically, the global flag returns the match across the entire string, or said another way: stops after finding the first match.

The result was that instead of getting groups returned, I was getting an array with one match for the string and it was the entire matching string (i.e. the whole link)!

Dropping the g flag (and the m wasn’t actually necessary for how I was using it) from my pattern worked like a charm!

function parseTitle(rowTitle) {
  const pattern = /!?\[([^\]]*)\]\(([^\)]+)\)/

  const groups = rowTitle.match(pattern)
  return groups
}

const title = `[test](google.com)`
console.log(parseTitle(title)) // ["[test](google.com)", "test", "google.com"]

Woot! And now my patterns are matching just as expected!


Related Posts
  • RegEx: Grouping Matches


  • Hi there and thanks for reading! My name's Stephen. I live in Chicago with my wife, Kate, and dog, Finn. Want more? See about and get in touch!