Vanilla JavaScript string startsWith

— 3 minute read

permalink

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

Using startsWith function in JavaScript permalink

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)

var 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 would return false:

var 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 permalink

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.

var 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

Feel free to play with this Codepen:

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

Browser Support permalink

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

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