Reg Exp Not Working with matchAll

Trying to get all delimited items in a string.

Here’s the code:

const myString = "abc{{HELLO}}defg{{WORLD}}"
const templateFieldsRegex = /\{\{\w+\}\}/g
const templateFields = myString.matchAll (templateFieldsRegex)

I expect to get array [“{{HELLO}}”, “{{WORLD}}”]
Not getting any results.

also posted here:
https://forum.freecodecamp.org/t/reg-exp-not-working-with-matchall/579873

1 Like

myString.matchAll returns an iterator

const matches = myString.matchAll(/\{\{\w+\}\}/g)

for (const match of matches) {
  console.log(match)
}

outputs
// ['{{HELLO}}', index: 3, input: 'abc{{HELLO}}defg{{WORLD}}', groups: undefined]
// ['{{WORLD}}', index: 16, input: 'abc{{HELLO}}defg{{WORLD}}', groups: undefined]

string.match should give you what you want, returning an Array.

1 Like

For extra credit: How to exclude the surrounding braces from the output?

You tell us.

3 Likes

Another approach could be to use named capturing groups.

// named capture group e.g (?<name>expression)
const re = /\{{2}(?<message>[^}]+)\}{2}/g

const strg = 'abc{{HELLO}}defg{{WORLD}}'

const matches = strg.matchAll(re)

// destructuring groups from match
for (const {groups} of matches) {
  console.log(groups.message)
}

// HELLO
// WORLD
1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.