0
0
JavascriptHow-ToBeginner · 3 min read

How to Use startsWith and endsWith in JavaScript

In JavaScript, use startsWith() to check if a string begins with a specific substring, and endsWith() to check if it ends with one. Both methods return true or false depending on the match.
📐

Syntax

The startsWith() and endsWith() methods are called on a string. They take a substring as the first argument to check for. Optionally, startsWith() can take a second argument to specify the position to start checking from.

  • str.startsWith(searchString[, position])
  • str.endsWith(searchString[, length])

Both return a boolean: true if the string starts or ends with the given substring, otherwise false.

javascript
str.startsWith(searchString[, position])
str.endsWith(searchString[, length])
💻

Example

This example shows how to use startsWith() and endsWith() to check parts of a string.

javascript
const text = 'Hello, world!';

console.log(text.startsWith('Hello'));    // true
console.log(text.startsWith('world'));    // false
console.log(text.endsWith('world!'));      // true
console.log(text.endsWith('Hello'));       // false

// Using position argument with startsWith
console.log(text.startsWith('world', 7));  // true
Output
true false true false true
⚠️

Common Pitfalls

Common mistakes include:

  • Not remembering that startsWith() can take a position argument, which changes where it starts checking.
  • Using endsWith() with a length argument incorrectly; it treats the string as if it were that length.
  • Trying to use these methods on non-string types without converting them first.

Both methods are case-sensitive, so 'Hello' and 'hello' are different.

javascript
const str = 'JavaScript';

// Wrong: case mismatch
console.log(str.startsWith('java')); // false

// Right: exact case
console.log(str.startsWith('Java')); // true

// Wrong: using endsWith length incorrectly
console.log(str.endsWith('Script', 9)); // false because length 9 means 'JavaScrip'

// Right: correct length
console.log(str.endsWith('Script', 10)); // true
Output
false true false true
📊

Quick Reference

Summary of startsWith() and endsWith() usage:

MethodPurposeArgumentsReturns
startsWith(searchString, position?)Checks if string starts with searchStringsearchString (string), position (optional number)true or false
endsWith(searchString, length?)Checks if string ends with searchStringsearchString (string), length (optional number)true or false

Key Takeaways

Use startsWith() to check if a string begins with a specific substring.
Use endsWith() to check if a string ends with a specific substring.
Both methods return true or false and are case-sensitive.
startsWith() accepts an optional position to start checking from.
endsWith() accepts an optional length to consider the string up to.