How to check if a string starts with substring in JavaScript

Last updated on Sep 14, 2020 by Suraj Sharma

In this tutorial, you will learn how you can check if a JavaScript string starts with a substring.

4 ways to check if a string starts with a substring in JavaScript.

1. Using String.startsWith() method

The startsWith() method determines whether a JavaScript string starts with a specific substring or not. It returns true if the string begins with the substring else it returns false.

'string starts with'.startsWith('str') // true

'string starts with'.startsWith('string') // true

'string starts with'.startsWith('starts') // false

We can pass a second parameter to the startsWith() method, to begin searching for the substring from the given start index. Default start index is 0.

'string starts with'.startsWith('star', 7) // true

'string starts with'.startsWith('star', 0) // false

It was introduced in ES6 and is not supported in Internet Explorer and some other old browsers.

2. Using String.substring() method

The substring() method returns a substring between the start and the end indexes, if the end index is not provided it takes the length of the string as the end index.

We can use the substring() method to check if a string starts with a substring by passing the length of the substring as an end index and 0 as a start index, the returned substring should be equal to the substring.

'javascript substring method'.substring(0, 'method'.length) === 'method'
// false

'javascript substring method'.substring(0, 'javascript'.length) === 'javascript'
// true

'javascript substring method'.substring(0, ' '.length) === ' '
// false

3. Using String.slice() method

The slice() method also returns a substring between the start and the end indexes just like the substring() method.

'javascript slice method'.slice(0, 'ja'.length) === 'ja'
// true

'javascript slice method'.slice(0, 'a'.length) === 'a'

// false

4. Using String.lastIndexOf() method

The lastIndexOf() method returns the index of the last occurrence of the string.

It starts searching for the substring backward from fromIndex, provided as a second parameter, it returns -1 if the substring is not found.

'Javascript String'.lastIndexOf('script', 0) // -1

'Javascript String'.lastIndexOf('Java', 0) // 0

Related Solutions

Rate this post

Suraj Sharma is a Full Stack Software Engineer. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.