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

Time:11-24

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

CodePudding user response:

Looks like you need a regular expression with a word boundary \b. You can create this regexp dynamically from your array:

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

const re = RegExp('\\b('   array.join('|')   ')\\b')

test = `
show vacuum bed_temperature_1
show vacuum bed_temp_2
show vacuum bed_temp3
show vacuums bed_temperature_1
shows vacuum bed_temperature_1
show vauum bed_temp3
`

console.log(test.trim().split('\n').map(s => s   ' = '   re.test(s)))

Note: if your array contains symbols that are special to regexes, they should be properly escaped.

CodePudding user response:

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");
  }
})
  • Related