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

is this all the code? Where is recordHTML defined?
if this is an fcc challenge, please post a link to it for context.

post is corrected.
i don’t know what fcc challenge is.

by “delimeted items” do you mean that you want to get everything that is inside the curly braces? (is that the rule?)

yes, that is the rule.

try using .match instead of .matchAll

I tested the following and it worked:

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

And the result from this was:
[“{{HELLO}}”,“{{WORLD}}”]

If you want to use matchAll, then you will get back an iteratable so you must iterate over the result to see all the matches.

Add the following to your code after your third line.

console.log([...templateFields])

Spreading out the iterable, creates an array of the matches.

The other option is to do:

const templateFields = [ ...myString.matchAll (templateFieldsRegex) ]
console.log(templateFields)

great!
so without your addition, what is templateFields?
When i try to examine it, i don’t see the data inside it.

After the spreading code, it seems to be an array of objects, where each element is an object, and that object contains just one property.

thx!

Thx! match is the fix.
The spreading method is also useful, but i just needed an array.

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

You can use non-capture groups to not include the brackets.

1 Like

templateFields is the result of matchAll which is an iterable < Iterators and generators - JavaScript | MDN>

1 Like