by Sai gowtham

Checking if a string starts with another string in JavaScript

In this tutorial, we are going to learn two different ways to check if a string starts with a specified string in JavaScript.

First way

The startsWith() method in JavaScript takes the search string as its first argument and check whether a given string starts with a search string and returns true if the string is found; otherwise it returns false.

Syntax:

String.prototype.startsWith(searchstring,position)

Example:

const str = 'this is my name'

console.log(str.startsWith('this'))

// true

By default, the string searching starts from position 0. We can also change its position by passing the second argument.

const str = 'this is my name'

console.log(str.startsWith('my',8)) // true

console.log(str.startsWith('my')) // false

Second way

The includes() method returns true, if a search string found in the given string, otherwise it returns false.

const str = 'hey buddy this is awesome place';

console.log(str.includes('is')) // true

console.log(str.includes('place')) // true

console.log(str.includes('notfound')) //  false

Note: The above two methods are case-sensitive.

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
45,614 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
284,472 students enrolled
40 hours of video content
View Course
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
130,921 students enrolled
21 hours of video content
View Course