如果字符串以某些值开头,是否可以排除它?

时间:2019-05-15 04:01:08

标签: javascript ecmascript-6

有什么方法可以检查数组中的任何值是否以任何值开头?

var value = "background-color";
var value2 = "--my-variable";

var excludeItems = ["--", "-", "_"];

if (does value starts with excludeItems) {
    // then exclude
}

2 个答案:

答案 0 :(得分:2)

检查数组中的.some个项目是否通过了针对字符串的startsWith测试:

var value1 = "background-color";
var value2 = "--my-variable";

var excludeItems = ["--", "-", "_"];

const v1excluded = excludeItems.some(str => value1.startsWith(str));
const v2excluded = excludeItems.some(str => value2.startsWith(str));

console.log(v1excluded, v2excluded);

在这种情况下,由于以--开头的字符串也必须以-开头,因此您可以将--完全排除在excludeItems数组之外,如果需要的话。

如果excludeItems是静态的,并且您要测试的字符很多,则可以使用正则表达式和字符集更简洁地完成操作:

var value1 = "background-color";
var value2 = "--my-variable";

const excludeItems = /^[-_!@#$%]/;

const v1excluded = excludeItems.test(value1);
const v2excluded = excludeItems.test(value2);

console.log(v1excluded, v2excluded);

答案 1 :(得分:2)

沿着“某些性能”的答案,您还可以使用像[value1, value2].filter(val => excludeItems.some(str => val.startsWith(str)))

这样的单线纸。

var value1 = "background-color";
var value2 = "--my-variable";

var excludeItems = ["--", "-", "_"];

const excluded = [value1, value2].filter(val => excludeItems.some(str => val.startsWith(str)));

const included = [value1, value2].filter(val => !excludeItems.some(str => val.startsWith(str)));

console.log(excluded);
console.log(included);