DEV Community

Samantha Ming
Samantha Ming

Posted on • Originally published at samanthaming.com

String startsWith() Method in JavaScript

CodeTidbit by SamanthaMing.com

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Multiple Characters

const name = 'Samantha Ming';

name.startsWith('Sam'); // true
name.startsWith('Min'); // false
Enter fullscreen mode Exit fullscreen mode

Multiple Words

const name = 'Samantha Ming';

name.startsWith('Samantha M'); // true
name.startsWith('antha Min'); // false
Enter fullscreen mode Exit fullscreen mode

Entire String

const name = 'Samantha Ming';

name.startsWith('Samantha Ming'); // true
Enter fullscreen mode Exit fullscreen mode

Exceeding String's Length

const name = 'Samantha Ming';

name.startsWith('Samantha Ming is the best'); // false โ† ๐Ÿ˜…
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

Thanks: @abraham

Using Regex

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

// OR
(/^some/).test('some string');
Enter fullscreen mode Exit fullscreen mode

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';
Enter fullscreen mode Exit fullscreen mode

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.

Resources


Thanks for reading โค
Say Hello! Instagram | Twitter | Facebook | Blog | SamanthaMing.com

Top comments (6)

Collapse
 
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.

Collapse
 
samanthaming profile image
Samantha Ming

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 ๐Ÿ™‚

Collapse
 
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.

Collapse
 
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!

Collapse
 
samanthaming profile image
Samantha Ming

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?

Collapse
 
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!