1

my code is supposed to match all of the key names that contain the inputted string. however when i enter "o" it wont match jordanMichael but will match noahsinnott and bobross. does anyone know why? this also happens when i enter 0 as it only matches noah when harry styles also has a zero in his key. when matched with no string it also returns all the keys so i know it is defiantly running him through the test but for some reason he never passes.

var adressLog = {
  NoahSinnott07484743803: {
    firstName: "Noah",
    lastName: "Sinnott",
    number: 07484743803,
    adress: "st michaels house, church street, billinghay"
  },

  HarryStlyes08674563827: {
    firstName: "Harry",
    lastName: "Styles",
    number: 08674563827,
    adress: "23 Merry gold lane, new-york"
  },

  BobRoss67543456754: {
    firstName: "Bob",
    lastName: "Ross",
    number: 67543456754,
    adress: "93 Scrooby Rd, Bircotes, Doncaster DN11 8JN"
  },

  JordanMichael78675678765: {
    firstName: "Jordan",
    lastName: "Michael",
    number: 78675678765,
    adress: "2700 Point Dr, Highland Park, IL 60035"
  }
};

function match(str) {
  a = new RegExp(str, "ig");
  let matches = [];
  let length = Object.keys(adressLog).length;
  for (let p = 0; p < length; p++) {
    current = Object.keys(adressLog)[p];
    if (a.test(current) == true) {
      matches.push(current);
    }
  }
  console.log(matches);
}
match("o");
Barmar
  • 669,327
  • 51
  • 454
  • 560
ns121
  • 37
  • 2
  • It seems to not be the your last match! – phuzi May 31 '22 at 17:05
  • 1
    It's an imho unintuitive side of javascript regex, which a lot of people bump into once - then they know. – ASDFGerte May 31 '22 at 17:13
  • Is there a reason you're using a regexp in the first place? Do you really need to match regular expression patterns rather than just look for substrings? – Barmar May 31 '22 at 17:52

0 Answers0