String startsWith() Method in JavaScript

Samantha Ming
DailyJS
Published in
3 min readJul 1, 2019

--

CodeTidbit by SamanthaMing.com

If you ever need to check if a string begins with another string, use ES6’s startsWithmethod. 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:

  1. Search Value
  2. 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

Multiple Characters

--

--

Samantha Ming
DailyJS

Frontend Developer sharing weekly JS, HTML, CSS code tidbits🔥 Discover them all on samanthaming.com 💛