【发布时间】:2022-11-23 22:02:09
【问题描述】:
我在尝试查找字符串中的子字符串时遇到问题。这不是使用 indexOf 或 match() 或 test() 或 includes() 的简单子字符串匹配。我试过使用这些但无济于事。我在数组中有一堆字符串,然后需要使用 filter() 方法或 some() 方法来查找子字符串匹配。
我需要用命令匹配数组中的一个字符串;
我尝试了以下但它不起作用:
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.
}
可接受的字符串
元素“show vacuum”与命令完全匹配。
const example1 = "show vacuum";
const example2 = "show vacuum bed_temperature_1";
const example3 = "show vacuum bed_temp_2";
const example4 = "show vacuum bed_temp3";
不可接受的字符串
const example 1 = "show vacuums bed_temperature_1";
const example 2 = "shows vacuum bed_temperature_1";
const example 3 = "show vauum bed_temp3";
【问题讨论】:
-
不确定您的 includes 行如何不起作用。不确定你为什么这样做
if() match lineinclude 的问题是它会寻找那个字符串,它不会关心“foo”在“food”中。如果需要精确匹配,则需要使用正则表达式。 -
我的不好,我意识到我使用了过于复杂的代码并稍微简化了它。
标签: javascript arrays substring indexof