String .startsWith() / endsWith() Since: ES6(ECMAScript 2015)
Checks whether a string begins or ends with a specified string. Returns true or false.
Syntax
// Checks whether the string begins with the specified string.
string.startsWith("searchString")
string.startsWith("searchString", startPosition)
// Checks whether the string ends with the specified string.
string.endsWith("searchString")
string.endsWith("searchString", length)
Method List
| Method | Description |
|---|---|
| startsWith("searchString") | Returns true if the string begins with the specified string, or false if it does not. |
| startsWith("searchString", startPosition) | Treats the specified position as the start of the string before checking. |
| endsWith("searchString") | Returns true if the string ends with the specified string, or false if it does not. |
| endsWith("searchString", length) | Checks the end of the string within the range of the specified number of characters from the beginning. |
Sample Code
var url = "https://wp-p.info/index.php";
// Checks whether the URL starts with "https".
console.log(url.startsWith("https")); // Outputs 'true'.
console.log(url.startsWith("http://")); // Outputs 'false'.
// Checks whether the URL ends with ".php".
console.log(url.endsWith(".php")); // Outputs 'true'.
console.log(url.endsWith(".html")); // Outputs 'false'.
// Checks with a specified start position.
console.log(url.startsWith("wp-p", 8)); // Starts checking from position 8, so outputs 'true'.
// Checks the end within a specified length.
var filename = "report_2026.pdf";
console.log(filename.endsWith("2026", 11)); // Checks within the first 11 characters and outputs 'true'.
Overview
string.startsWith() checks whether the beginning of a string matches a specified string, and string.endsWith() checks whether the end matches. Previously you had to use string.indexOf() to determine the position, but these methods let you write such checks more intuitively.
They are especially useful for tasks like checking a URL's protocol or verifying a file extension. Both methods are case-sensitive, so if you need a case-insensitive comparison, convert the string with string.toLowerCase() first.
If you only need to check whether a string contains a particular substring anywhere within it, string.includes() is the better choice.
Browser Compatibility
40 or earlier ×
16 or earlier ×
Android Browser
42+ ○
36 or earlier ×
Chrome Android
41+ ○
35 or earlier ×
Firefox Android
79+ ○
16 or earlier ×If you find any errors or copyright issues, please contact us.