I am working with regular expressions in Node.js, and I’m trying to match words in a line of text. I’m trying to use matchAll as I want to do something with all words in each line. However, I get the error "TypeError: line.matchAll is not a function" when I call matchAll.
I’ve tried calling matchAll in different ways, wondering if I called it incorrectly (I’m new to Node.js) but that just resulted in other errors. Here’s the relevant section of my code:
const regex = /[a-zA-Z']{2,}/g
var leftOver = '';
var read, line, idxStart, idx;
while((read = fs.readSync(fd, buf, 0, bufSize, null)) !== 0) {
leftOver += buf.toString('utf-8', 0, read);
idxStart = 0;
while((idx = leftOver.indexOf("\n", idxStart)) !== -1) {
line = leftOver.substring(idxStart, idx).toLowerCase;
let wordsInLine = line.matchAll(regex); // this is where I get my error
for(word of wordsInLine) {
// do something
}
idxStart = idx + 1;
}
leftOver = leftOver.substring(idxStart);
}
I’ve looked for other answers, but everything I’ve seen just says matchAll is only available in Node.js v12.0 up, and that isn’t my issue, as I’m using Node.js v18.
>Solution :
These two statements are the culprit:
line = leftOver.substring(idxStart, idx).toLowerCase;
let wordsInLine = line.matchAll(regex);
In the first one you set the value of line to be a method. That method being String.prototype.toLowerCase. It is no more a string.
Fix this, by executing the method:
line = leftOver.substring(idxStart, idx).toLowerCase();
let wordsInLine = line.matchAll(regex);