-1

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";
Yildirim
  • 25
  • 4
  • 1
    unsure how your includes line does not work. Not sure why you are doing that `if() match line` Problem with includes is it will look for that string, it will not care that "foo" is in "food". If you need exact match, you need to use a regular expression. – epascarello Nov 23 '22 at 13:31
  • My bad, I realise I used overly complex code and dumbed it down slightly. – Yildirim Nov 23 '22 at 13:36

2 Answers2

3

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.

gog
  • 10,367
  • 2
  • 24
  • 38
  • This should come with the caveat about synthesizing a regular expression with something like `array.join('|')` because you're intending to create a regular expression that matches the literal text of the elements of the array, but aren't escaping any special regular expression syntax or characters that may appear in the text of those array elements. – Wyck Nov 23 '22 at 13:41
-1
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");
  }
})
Nuh Ylmz
  • 24
  • 3