Open In App

JavaScript String startsWith() Method

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

The JavaScript String startsWith() method checks if a string starts with the characters of a specified string.

Syntax:

str.startsWith( searchString , position )

Parameters:

This method accepts two parameters as mentioned above and described below: 

  • searchString: It is a required parameter. It stores the string that needs to be searched.
  • start: It determines the position in the given string from where the searchString is to be searched. The default value is zero.

Return value:

This method returns the Boolean value true if the searchString is found else returns false.

String startsWith() Examples

Example 1: Checking if a String Starts with a Specific Substring

The function checks if the string ‘str’ starts with the substring ‘Gee’. It returns true because ‘Geeks for Geeks’ starts with ‘Gee’.

JavaScript
function func() {
    let str = 'Geeks for Geeks';
    let value = str.startsWith('Gee');
    console.log(value);
}
func();

Output
true

Example 2: Checking if a String Starts with a Specific Substring at a Given Position

The function checks if the string ‘str’ starts with the substring ‘great’ starting from index 8. It returns true because ‘great day.’ starts at index 8 in the string.

JavaScript
// JavaScript to illustrate
// startsWith() method
function func() {

    // Original string
    let str = 'It is a great day.';
    let value = str.startsWith('great', 8);
    console.log(value);
}

// Function call
func();

Output
true

Example 3: Checking if a URL or Filename Starts with a Specific Substring

The code checks if the URL starts with “https://” and if the filename starts with “.js”. It returns true for the URL starting with “https://” and false for the filename starting with “.js”.

JavaScript
// Checking if a URL starts with "https://"
let url ='https://www.geeksforgeeks.org/';

console.log(url.startsWith('https://')); 
console.log(url.startsWith('http://'));

//Checking if a filename starts with a specific extension
let filename = 'script.js';

console.log(filename.startsWith('.js')); 
console.log(filename.startsWith('script.'));

Output
true
false
false
true

We have a complete list of Javascript String Methods, to check those please go through the Javascript String Complete Reference article.

Supported Browser:


Last Updated : 14 Mar, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads