Vanilla JavaScript string startsWith

โœ๏ธ

Learn in this guide how to use the Vanilla JavaScript string.startsWith() function. See the code examples in the Codepen!

5 May, 2020 ยท 2 min read

A very nifty function in JavaScript is the startsWith() function. We can use this function to see if a string starts with a substring.

Javascript String startswith

To use the function, we need to have a string. Then we can call the string.startsWith('substring') function and we will get a boolean value in return (true/false). The boolean confirms if the substring can be found at the beginning of the basestring.

const string =
  "Your time is limited, so don't waste it living someone else's life";

// Check if it starts with `Your time`
console.log(string.startsWith('Your time'));
// true

Important to know is that the startsWith method is case sensitive. So the following search string would return false:

const string =
  "Your time is limited, so don't waste it living someone else's life";

// Check if it starts with `your time`
console.log(string.startsWith('your time'));
// false

Using an offset search position on startsWith

We now used the basic startsWith() function, but it accepts another parameter; the starting position. So let's assume our string always starts with "Your time" but we want to see if the string after that is "is limited". We can do so by offsetting the position.

const string =
  "Your time is limited, so don't waste it living someone else's life";

// Check if it starts with `is limited`
console.log(string.startsWith('is limited', 10));
// true

See the code examples in this Codepen

Feel free to try the JavaScript code here:

See the Pen Vanilla JavaScript string startsWith by Chris Bongers (@rebelchris) on CodePen.

Browser Support

This function works in all browsers but not in IE ๐Ÿ˜ข. We can use this polyfill to help IE.

Thank you for reading, and let's connect!

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter

Spread the knowledge with fellow developers on Twitter
Tweet this tip
Powered by Webmentions - Learn more

Read next ๐Ÿ“–

JavaScript sending data between windows

9 Sep, 2022 ยท 4 min read

JavaScript sending data between windows

Using the native payment request JavaScript API

9 Aug, 2022 ยท 8 min read

Using the native payment request JavaScript API