MattClaff
MattClaff

Reputation: 685

How to find all handlebar partials in a file using regex

The expression I have been using works in regExr but when I run my code in node it just returns one partial instead of an array of partials.

My Node file

'use strict';
var fs = require('fs');

module.exports = function() {
  fs.readFile('text.txt', 'UTF8', function(err, contents) {
    if(err) throw err;

    var re = /({{> (\w*)}})/g;
    var myArray = re.exec(contents);

    console.log(myArray);
  });
}();

Text.txt

{{> test}}

{{> test2}}

{{> test3}}

My returned result is just {{> test}}

Upvotes: 0

Views: 453

Answers (1)

Vincent Schöttke
Vincent Schöttke

Reputation: 4716

If you use .exec() you need to call it in a loop until it returns null to get all matching results. To simply get the matches in an array use .match on the contents instead:

'use strict';
var fs = require('fs');

module.exports = function() {
  fs.readFile('text.txt', 'UTF8', function(err, contents) {
    if(err) throw err;

    var re = /({{> (\w*)}})/g;
    var myArray = contents.match(re);

    console.log(myArray);
  });
}();

Upvotes: 1

Related Questions