How to check if a string starts with another string in JavaScript
Checking if strings start with specific prefixes is crucial for URL validation, file type detection, protocol checking, and implementing features like autocomplete or command parsing in JavaScript applications.
With over 25 years of experience in software development and as the creator of CoreUI, I’ve implemented prefix checking extensively in components like search filters, file uploads, and routing systems where determining string beginnings is essential for proper functionality.
From my extensive expertise, the most modern and intuitive solution is using the ES6 startsWith()
method, which provides a clear boolean result.
This approach is readable, efficient, and specifically designed for prefix detection with excellent performance characteristics.
Use the startsWith()
method to check if a string begins with a specific substring.
const text = 'Hello world'
const startsWithHello = text.startsWith('Hello')
// Result: true
The startsWith()
method checks if the string begins with the specified substring and returns true
if it does, or false
otherwise. In this example, 'Hello world'.startsWith('Hello')
returns true
because the string indeed starts with ‘Hello’. The method is case-sensitive, so text.startsWith('hello')
would return false
. You can optionally specify a starting position as a second parameter: text.startsWith('world', 6)
checks if ‘world’ appears starting at index 6.
Best Practice Note:
This is the same approach we use in CoreUI components for validating URLs, checking file extensions, and implementing prefix-based filtering across our component library.
For case-insensitive checking, convert both strings to lowercase first: text.toLowerCase().startsWith(prefix.toLowerCase())
. For older browser support, use the alternative: text.indexOf(prefix) === 0
. The startsWith()
method is supported in all modern browsers and provides cleaner syntax than index-based alternatives.