JavaScript String startsWith() Method (original) (raw)
Last Updated : 11 Jul, 2024
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 `
let str = 'Geeks for Geeks'; let value = str.startsWith('Gee');
console.log(value);
`
**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
// Original string let str = 'It is a great day.'; let value = str.startsWith('great', 8);
console.log(value);
`
**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
**Supported Browser:
- Google Chrome 41
- Edge 12
- Firefox 17
- Opera 28
- Safari 9