startsWith method
ES6 introduces the startsWith
method to the String object, it checks whether or not a string starts with certain characters.
In ES5 we can use the indexOf
method which works fine. It’s just not very clear at first glance what it does.
const lipsum = 'lorem ipsum dolor sit amet';
const check = lipsum.indexOf('l') === 0;
// true
console.log(check);
startsWith
does exactly the same, but looks a lot cleaner and is much easier to read. Even if you’re not an experienced developer, its pretty clear what this code does.
const lipsum = 'lorem ipsum dolor sit amet';
const check = lipsum.startsWith('l');
// true
console.log(check);
The params
Nice and simple, there’s just the two:
searchValue
– the string you want to search forstartPosition
– the index to start at (optional)
searchValue
The first parameter can be a single character or a longer string.
const lipsum = 'lorem ipsum dolor sit amet';
// true
lipsum.startsWith('l');
lipsum.startsWith('lored ipsum');
// false
lipsum.startsWith('i');
If searchValue
is longer than the string itself, it will return false.
// false
lipsum.startsWith('lorem ipsum dolor sit amet, consectetur');
It’s also case sensitive, it must exactly match to return true.
// false
lipsum.startsWith('Lorem');
startPosition
By default it’ll start at the first character (position 0 since JavaScript is zero-indexed). We can override this by passing a second parameter.
In this example we’ll run the check against the second character.
// true
lipsum.startsWith('o', 1);