Refactoring some code that uses string.startsWith() in JavaScript. Docs don't say you can use wildcard or Regular Expression. What is alternative?
string.prototype.match
and regex.prototype.test
.
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);
let a = /^[gh]/.test('hello'); // true
let b = /^[gh]/.test('gello'); // true
let c = /^[gh]/.test('ello'); // false
console.log(a, b, c);
The regex symbol ^
ensures the regex matches only at the string start.