DEV Community


String startsWith() Method in JavaScript

samanthaming profile image Samantha Ming Originally published at ・3 min read

CodeTidbit by

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:

  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

const name = 'Samantha Ming';

name.startsWith('Sam'); // true
name.startsWith('Min'); // false

Multiple Words

const name = 'Samantha Ming';

name.startsWith('Samantha M'); // true
name.startsWith('antha Min'); // false

Entire String

const name = 'Samantha Ming';

name.startsWith('Samantha Ming'); // true

Exceeding String's Length

const name = 'Samantha Ming';

name.startsWith('Samantha Ming is the best'); // false ← 😅

2. Starting Index

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.

Default Index (0)

const name = 'Samantha Ming';

name.startsWith('S'); // true
name.startsWith('S', 0); // true

Start at the 1st index

For those new to programming. Please note that JavaScript is zero-based. Meaning the count begins at 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

Start at the 2nd index

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

Negative Starting Index

So negative index won't work. I was trying to be clever to test if negative index would work similarly like slice() where if you pass a negative index, it would be the last character. Proof again, don't think you can outsmart JavaScript 😂

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 😜

Case Sensitive

One important thing to keep in mind is the startWith method is case sensitive.

const name = 'Samantha Ming';

name.startsWith('sam'); // false

Browser Support

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.

Browser Support

Community Inputs

💬 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 👀

Using Search

const lunch = '🥗🥪☕️';
const search = '🥗';
lunch.slice(0, search.length) === search;

Thanks: @abraham

Using Regex

'some string'.match(/^some/);

// OR
(/^some/).test('some string');

Thanks: @cpt_silverfox

Using Bracket

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[0] === 'h';

Thanks: @neutrino2211

Performance Check

@gwardwell: Here’s one such test (found on JSPerf, I didn’t author it) that would indicate indexOf blows startsWith away.


Thanks for reading ❤
Say Hello! Instagram | Twitter | Facebook | Blog |

Discussion (6)

Editor guide
prahladyeri profile image
Prahlad Yeri • Edited

I can understand all the excitement about these new ways but folks, remember that many enterprise users are still stuck on older versions of IE and Windows 7. On the server side, there are many who haven't migrated from Ubuntu 12.04/14.04 LTS versions and those old versions of node don't yet support the startsWith & endsWith fancy methods and you still have to deal with the old indexOf!

As a dev, you should ideally know both but if you are limited on brain resources, the advantage of using indexOf is that it works on both old and new versions of JS. Especially if you still happen to support enterprise users, the knowledge of the old ways still helps! There will be a time for upgrading to these newer methods, but that time still hasn't come yet.

samanthaming profile image
Samantha Ming Author

Totally, you should not dismiss supporting old browser. There are a lot of folks especially in the public section using IE or older browser. I think that’s where polyfill or something like Babel come into play 👍 it doesn’t deprive the better dev experience of using the newer syntax and still give you support of older browsers 🙂

ssimontis profile image
Scott Simontis

Polyfills to the rescue! I'd rather have all the abstractions out there available to my team so that they can use what works best for them than limit them to support customers using legacy technology. I have no problem pushing a larger paload or slower performance on legacy users for my software; I think it helps incentivize change. A lot of times when someone comes to me with an IE10 bug or something similar, it would be cheaper to buy that person an Intel Atom PC than it is to pay a programmer to diagnose, fix, and test the issue.

ssimontis profile image
Scott Simontis

I think that the way you write would make it very natural for you to write examples as tests. This hit me when you tested to see if negative indexes worked.

I find that writing test cases makes learning new programming languages more interesting. Whenever I have to go through the basics in a programming language I skim through so quickly that I can't remember whatever subtle differences exist between my normal arsenal of languages and the new one. It's also a great reference that you can look back on if you forget how a feature works.

If you've never played around with testing frameworks in JavaScript, Jest is the most popular framework out there and there are a lot of great resources for it. I would highly encourage you to play around with it, I think it will help you grow a lot, and you can write an article or two about any gotchas you encountered!

samanthaming profile image
Samantha Ming Author

Totally! Testing is something I’m finally diving into. I know, it should of be part of my early career 😓. With my new job, I’ve been working in Jest, jasmine, and RSpec. Funny how I went from 0 testing to tackle all 3 at once 😅. Do you have any good testing tutorial you’d recommend?

ssimontis profile image
Scott Simontis

I did not find a tutorial when I first learned JS testing...I pre tended I knew what I was doing and frantically figured it out one weekend! I was building the most complex UI components I have ever dealt with (it was the interface to customize sandwiches when ordering online from as restaurant) and ended up with 2000 lines of KnockoutJS because I failed to convince my manager that React was a smart choice.

2000 lines of code is hard enough to keep track of on its own. I essentially used a Redux-like system via custom message passing to make the component work, and it was so difficult trying to trace the execution flow through all that code. I knew I needed some tests so I could prove that at least some of it worked correctly!

I began adapting functional programming principles through Lodash and I was starting to clean things up enough that I had pure functions (no side effects, deterministic input) ready to test. I couldn't figure out Webpack (still struggle to this day to do so!) and my tooling knowledge was pretty weak, so I chose QUnit because it seemed easiest.

It was not a pretty experience, but it taught me a lot having to figure out how to set up all these components myself and add it to my Gulpfile and teach the rest of the team how to test if they wanted to. Sometimes you have to let life be tutorial!