Skip to content
Advertisement

How do I find an exact substring match in an array in JavaScript?

I’m having trouble trying to find a substring within a string. This isn’t a simple substring match using indexOf or match() or test() or includes(). I’ve tried using these but to no avail. I have a bunch of strings inside an array, and then either need to use filter() method or the some() method to find a substring match.

I need to match a string in the array with the command;

I tried the following but it doesn’t work:

let matchedObject;
const command = "show vacuum bed_temperature_1";
const array = [ "show vacuum", "show system", "set system", "set vacuum" ];

if (array.some((a) => command.includes(a))) {
    // This matches an element in the array partially correctly, only that it also matches with one of the unacceptable strings below.
}

Acceptable strings

The element “show vacuum” is an exact match with the command.

const example1 = "show vacuum";
const example2 = "show vacuum bed_temperature_1";
const example3 = "show vacuum bed_temp_2";
const example4 = "show vacuum bed_temp3";

Unacceptable strings

const example 1 = "show vacuums bed_temperature_1";
const example 2 = "shows vacuum bed_temperature_1";
const example 3 = "show vauum bed_temp3";

Advertisement

Answer

const array = ["show vacuum", "show system", "set system", "set vacuum"];
const outputString = "show vacuum bed_temperature_1";

array.forEach((key) => {
  const regex = new RegExp(`${key}`);
  if (regex.test(outputString)) {
    console.log(key, "matched");
  } else {
    console.log(key, "not matched");
  }
})
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement