Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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";

>Solution :

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");
  }
})
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading