Search code examples
javascriptnode.jsecmascript-5

string.startsWith() Wildcard OR Regular Expression


Refactoring some code that uses string.startsWith() in JavaScript. Docs don't say you can use wildcard or Regular Expression. What is alternative?


Solution

  • string.prototype.match and regex.prototype.test.

    'string'.match(/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);

    The regex symbol ^ ensures the regex matches only at the string start.