String startsWith() Method in JavaScript
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 indexOf
🤓
I really like the direction JavaScript is going. Not just introducing all these helpful methods, but evolving the language to be more human readable. This is how we make tech more accessible. Make it easier to learn. Love it! 😍
const lunch = '🥗 🥪 🍮'// Old Way
lunch.indexOf('🥗') === 0 // true// ✅ ES6 Way
lunch.startsWith('🥗') // true
startsWith
() Parameters
The startsWith
method accepts 2 parameters:
- Search Value
- Starting Index
1. Search Value
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
Single Character
const name = 'Samantha Ming';name.startsWith('S'); // true
name.startsWith('M'); // false