To check if a string starts with another substring in JavaScript, you can use one of the following methods:
1. startsWith()
(Modern Approach – ES6+)
The startsWith()
method is the most straightforward and readable way to check if a string starts with a specific substring.
const str = "Hello, World!";
const substring = "Hello";
// Check if 'str' starts with 'substring'
console.log(str.startsWith(substring)); // true ✅
Features:
- Case-sensitive:
str.startsWith("hello")
→false
. - Optional Position: Start checking from a specific index:
str.startsWith("World", 7); // Starts at index 7 → true
- Handles Empty Strings:
str.startsWith("")
→true
.
2. indexOf()
(Legacy Support)
For environments that don’t support ES6, use indexOf()
to check if the substring starts at index 0
:
const str = "Hello, World!";
const substring = "Hello";
console.log(str.indexOf(substring) === 0); // true ✅
3. Regular Expressions (Advanced)
Use a regex to test if the string starts with a pattern (case-insensitive example):
const str = "Hello, World!";
const pattern = /^hello/i; // Case-insensitive check
console.log(pattern.test(str)); // true ✅
Key Considerations
Method | Pros | Cons |
---|---|---|
startsWith() | Clean syntax, direct purpose | ES6+ only (no IE support) |
indexOf() | Works in older browsers | Less intuitive |
Regex | Flexible for patterns | Overkill for simple checks |
Case-Insensitive Check
Convert both strings to lowercase before checking:
const str = "Hello, World!";
const substring = "hello";
// Case-insensitive check
console.log(str.toLowerCase().startsWith(substring.toLowerCase())); // true ✅
Polyfill for startsWith()
(Legacy Support)
Add support for older browsers:
if (!String.prototype.startsWith) {
String.prototype.startsWith = function(search, pos) {
pos = pos || 0;
return this.substr(pos, search.length) === search;
};
}
Example Workflow:
const url = "https://example.com";
// Check if URL uses HTTPS
if (url.startsWith("https://")) {
console.log("Secure connection!"); // ✅
}
// Legacy approach
if (url.indexOf("https://") === 0) {
console.log("Secure connection!"); // ✅
}
Summary:
- Modern code: Use
startsWith()
. - Legacy code: Use
indexOf() === 0
. - Case-insensitive needs: Normalize case with
toLowerCase()
.