I thought this code would work, but it didn’t.
Node.Js
const reply = "Isi seharga Rp 10.000, terima kasih.";
const localRegex = /I.*Rp (?<harga>.*)/;
const sql = 'SELECT regex FROM balasan WHERE nama="satu"';
db.query(sql, function (err, results) {
//if (err) throw err;
const regex = results[0].regex;
console.log(localRegex == regex ? true : false); //return true
console.log(regex);
const found = reply.match(regex);
console.log(found.groups);
});
Result: TypeError: Cannot read properties of null (reading ‘groups’).
What am I missing?
If I use localRegex, the result is correct.
2
Answers
I solved this by remove the slash from database.
I.*Rp (?<harga>.*)
. Even theconsole.log(localRegex == regex ? true : false);
return false. Thank you everyone.The error you’re facing means that the reply.match(regex) operation is returning null. That means there were no matches found in reply base on your provided regular expression pattern. I don’t see where you’ve also declared the reply variable.
So here are few suggestions.
Check if reply exist, if it doesn’t you’ll have to create the variable reply and make sure it’s a valid string you want to apply the regular expression on.
Check your regular expression in your database to see if it’s the correct expression you want to use.
Handle cases where there are no matches found to prevent the TypeError. Check the below code as a guide.
I hope this is helpful. Please give me a tick or accept as answer if it helps solve your problem