Question
How to Check Whether a String Starts With Another String in JavaScript
Question
How can I write the JavaScript equivalent of C#'s String.StartsWith?
For example:
var haystack = 'hello world';
var needle = 'he';
haystack.startsWith(needle) === true;
I want to check whether one string begins with another string. If native support is not available in some environments, what JavaScript approaches can be used instead?
Short Answer
By the end of this page, you will understand how to test whether a string begins with another string in JavaScript. You will learn the modern startsWith() method, older fallback techniques such as indexOf() and slice(), when to use each approach, and the common mistakes beginners make when comparing string prefixes.
Concept
In JavaScript, checking whether a string starts with another string means testing whether the beginning of one string matches a smaller string exactly.
For example, does 'hello world' begin with 'he'? Yes.
This is a very common string operation. It is used in many kinds of programs:
- validating user input
- checking URL paths
- filtering filenames
- detecting command prefixes
- parsing text-based data
Modern JavaScript provides a built-in method for this:
'hello world'.startsWith('he'); // true
Before this method became widely available, developers often used alternatives such as:
indexOf(...) === 0slice(...) === ...- regular expressions
Why this matters:
- It makes your code easier to read.
- It avoids manual character-by-character checks.
- It helps express intent clearly: you want a prefix match, not a general substring search.
A prefix check is stricter than asking whether a string merely contains another string somewhere in the middle. For example:
'hello world'.includes();
.();
Mental Model
Think of a string like a line of text on a label.
If you want to know whether the label starts with a word, you only look at the first few characters, not the whole label.
haystack= the full labelneedle= the prefix you want to check
Example:
- Full label:
hello world - Prefix to test:
he
You compare the first 2 characters of the label with he.
If they match exactly, the answer is true.
So startsWith() is like asking:
“Does this text begin with these exact characters?”
Not:
“Does this text contain these characters anywhere?”
Syntax and Examples
The modern syntax is:
string.startsWith(searchString)
You can also provide a starting position:
string.startsWith(searchString, position)
Basic example
const haystack = 'hello world';
const needle = 'he';
console.log(haystack.startsWith(needle)); // true
This checks whether haystack begins with needle.
Example with a different result
console.log('hello world'.startsWith('lo')); // false
'lo' exists in the string, but not at the beginning.
Using a starting position
text = ;
.(text.(, ));
Step by Step Execution
Consider this example:
const haystack = 'hello world';
const needle = 'he';
const result = haystack.startsWith(needle);
console.log(result);
Here is what happens step by step:
haystackis assigned the value'hello world'.needleis assigned the value'he'.haystack.startsWith(needle)checks whether'hello world'begins with'he'.- JavaScript compares the first 2 characters of
'hello world'with'he'. - The first 2 characters are
'he'. - They match exactly, so the expression returns
true. resultstorestrue.console.log(result)prints .
Real World Use Cases
Checking string prefixes appears in many practical situations.
URL routing
if (path.startsWith('/api/')) {
// handle API route
}
This helps separate API requests from normal page requests.
File type checks
if (fileName.startsWith('draft_')) {
console.log('This is a draft file');
}
Useful for naming conventions in scripts or build tools.
Command parsing
if (message.startsWith('/help')) {
showHelp();
}
Chat apps and bots often use prefixes to detect commands.
Input validation
if (!email.startsWith('admin@')) {
console.log('Not an admin email');
}
This can support simple checks before deeper validation.
Real Codebase Usage
In real projects, developers often use prefix checks in combination with broader patterns.
Guard clauses
A guard clause exits early when the input does not match an expected prefix.
function handleRoute(path) {
if (!path.startsWith('/admin')) {
return 'Not an admin route';
}
return 'Admin route';
}
This keeps code flatter and easier to read.
Validation
function isInternalId(id) {
return id.startsWith('INT-');
}
Prefix checks are often a first validation step.
Configuration-driven logic
const privatePrefix = 'private_';
function isPrivateKey(key) {
return key.startsWith(privatePrefix);
}
Instead of hardcoding values in many places, developers often store the prefix in configuration.
Fallback support for older environments
Common Mistakes
Here are common beginner mistakes when checking string prefixes.
Mistake 1: Using indexOf() without checking for 0
Broken code:
if ('hello world'.indexOf('he')) {
console.log('Starts with he');
}
Why this is wrong:
indexOf('he')returns00is falsy in JavaScript- so the
ifblock does not run
Correct version:
if ('hello world'.indexOf('he') === 0) {
console.log('Starts with he');
}
Mistake 2: Confusing includes() with startsWith()
Broken logic:
Comparisons
Here is how common prefix-checking approaches compare:
| Approach | Example | Best for | Notes |
|---|---|---|---|
startsWith() | str.startsWith('he') | Modern readable code | Clearest option |
indexOf() === 0 | str.indexOf('he') === 0 | Older compatibility | Works well but less expressive |
slice() comparison | str.slice(0, 2) === 'he' | Simple fallback logic | Good when you know the prefix length |
| Regular expression | /^he/.test(str) | Pattern matching |
Cheat Sheet
Quick reference
Modern method
str.startsWith(prefix)
str.startsWith(prefix, position)
Fallbacks
str.indexOf(prefix) === 0
str.slice(0, prefix.length) === prefix
Examples
'hello world'.startsWith('he'); // true
'hello world'.startsWith('lo'); // false
'JavaScript'.startsWith('Script', 4); // true
Case-sensitive
'Hello'.startsWith('he'); // false
Case-insensitive check
'Hello'.().();
FAQ
How do I check if a string starts with another string in JavaScript?
Use startsWith():
'hello world'.startsWith('he'); // true
What can I use instead of startsWith() in older JavaScript?
Use either:
str.indexOf(prefix) === 0
or:
str.slice(0, prefix.length) === prefix
Is startsWith() case-sensitive in JavaScript?
Yes. 'Hello'.startsWith('he') is false because uppercase and lowercase letters are different.
What is the difference between includes() and startsWith()?
includes()checks whether a string appears anywhere.- checks only the beginning.
Mini Project
Description
Build a small command parser that checks whether user input starts with specific prefixes such as /help, /login, and /logout. This demonstrates how prefix checking is used in real applications like chat tools, terminal-style interfaces, and bots.
Goal
Create a function that classifies input based on whether it starts with known command prefixes.
Requirements
- Create a function that accepts a text input.
- Return
'help'if the input starts with/help. - Return
'login'if the input starts with/login. - Return
'logout'if the input starts with/logout. - Return
'message'for any input that does not start with a known command.
Keep learning
Related questions
Adding Table Rows with jQuery: append(), Limits, and Best Practices
Learn how to add table rows in jQuery using append(), what elements are allowed in tables, and safer ways to build rows dynamically.
Bower vs npm: What’s the Difference in JavaScript Package Management?
Learn the plain difference between Bower and npm, how each manages packages, and why npm replaced Bower in most JavaScript projects.
Can `(a == 1 && a == 2 && a == 3)` Ever Be True in JavaScript?
Learn how JavaScript type coercion, loose equality, and custom object conversion can make `a == 1 && a == 2 && a == 3` true.