If you ever need to check if a string begins with another string, use ES6's
startsWith method. I really like this method because intuitively it's so comprehensive. Even if you don't know have any tech background, just by reading the code, you can more easily deduce what's happening in comparison to
const lunch = '🥗 🥪 🍮' // Old Way lunch.indexOf('🥗') === 0 // true // ✅ ES6 Way lunch.startsWith('🥗') // true
startsWith method accepts 2 parameters:
- Search Value
- Starting Index
This is a required field. Here is where you pass your search value. This can be a single character or longer. Let's see some examples
const name = 'Samantha Ming'; name.startsWith('S'); // true name.startsWith('M'); // false
const name = 'Samantha Ming'; name.startsWith('Sam'); // true name.startsWith('Min'); // false
const name = 'Samantha Ming'; name.startsWith('Samantha M'); // true name.startsWith('antha Min'); // false
const name = 'Samantha Ming'; name.startsWith('Samantha Ming'); // true
const name = 'Samantha Ming'; name.startsWith('Samantha Ming is the best'); // false ← 😅
So by default, your starting index is going to be
0. But with this parameter, you can make it start at a different starting position. Let's take a look at a few examples.
const name = 'Samantha Ming'; name.startsWith('S'); // true name.startsWith('S', 0); // true
0. So the first character is at
0 index, the second character is at
1 index 🤓
const name = 'Samantha Ming'; name.startsWith('am', 1); // true name.startsWith('am'); // false
Following our zero-based counting, the 2nd index is equal to the 3rd character.
const name = 'Samantha Ming'; name.startsWith('ma', 2); // true name.startsWith('ma'); // false
So negative index won't work. I was trying to be clever to test if negative index would work similarly like
const name = 'Samantha Ming'; name.startsWith('g', -1); // false
I guess that's what
endsWith is for. I'll cover this in a future tidbit 😜
One important thing to keep in mind is the
startWith method is case sensitive.
const name = 'Samantha Ming'; name.startsWith('sam'); // false
This is supported by all modern browser. Except for .... I'm sure you guessed it -- no Internet Explorer 😑. You will need to use a Polyfill or a compiler like Babel.
💬 What other way do you know of checking if a string begins with something?
This is the question I asked the community. Got some really good ones. Let's take a look 👀
const lunch = '🥗🥪☕️'; const search = '🥗'; lunch.slice(0, search.length) === search;
'some string'.match(/^some/); // OR (/^some/).test('some string');
If you're just checking for one singular character, you can try this. But note when you have more than character (ie. hel), this method won't work.
const word = 'hello'; word === 'h';
@gwardwell: Here’s one such test (found on JSPerf, I didn’t author it) that would indicate
- MDN Web Docs: startsWith
- w3schools: startsWith
- Stack Overflow: How to check if a string “StartsWith” another string?