string.startsWith() 通配符或正则表达式

string.startsWith() Wildcard OR Regular Expression

重构一些在 JavaScript 中使用 string.startsWith() 的代码。 Docs 不要说你可以使用通配符或正则表达式。什么是备选方案?

string.prototype.matchregex.prototype.test.

'string'.匹配(/regex/):

let a = 'hello'.match(/^[gh]/); // truthy (['h'])
let b = 'gello'.match(/^[gh]/); // truthy (['g'])
let c = 'ello'.match(/^[gh]/); // falsey (null)
console.log(a, b, c);

/regex/.test('string'):

let a = /^[gh]/.test('hello'); // true
let b = /^[gh]/.test('gello'); // true
let c = /^[gh]/.test('ello'); // false
console.log(a, b, c);

正则表达式符号 ^ 确保正则表达式仅在字符串开头匹配。