skip to Main Content

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


  1. Chosen as BEST ANSWER

    I solved this by remove the slash from database. I.*Rp (?<harga>.*). Even the console.log(localRegex == regex ? true : false); return false. Thank you everyone.


  2. 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.

    1. 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.

    2. Check your regular expression in your database to see if it’s the correct expression you want to use.

    3. Handle cases where there are no matches found to prevent the TypeError. Check the below code as a guide.

    const localRegex = /I.*Rp (?<harga>.*)/;
    const sql = 'SELECT regex FROM balasan WHERE nama="satu"';
    
    db.query(sql, function(err, results) {
      if (err) {
        console.error(err);
        return; // Handle the database query error
      }
    
      const regex = results[0].regex;
      console.log(localRegex == regex ? true : false); // Return true if regex patterns match
    
      // Ensure that reply is a valid string you want to match against. if you haven't created it outside the scope of this query, you may need to create it like below
      const reply = "I found Rp 100 in a text";
    
      const found = reply.match(regex);
      // handle cases where there's no matches found to get rid of the TypeError
      if (found !== null) {
        console.log(found.groups); // Access groups if a match was found
      } else {
        console.log("No match found."); // Handle the case where no match was found
      }
    });

    I hope this is helpful. Please give me a tick or accept as answer if it helps solve your problem

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search