JavaScript program to check string starts and ends is a common requirement when working with user input, file names, URLs, and data validation in web applications. Whether you are verifying a prefix, checking a suffix, or ensuring a string follows a specific format, this logic plays an important role in writing reliable JavaScript code.
In this blog, you will learn different ways to check whether a string starts and ends with certain characters in JavaScript. We’ll cover basic logic, modern ES6 methods, real-world examples, and common mistakes to avoid—making this guide useful for both beginners and experienced developers.
Why checking start and end characters in strings matters
Checking start and end characters helps you:
- Validate user input (email, username, file type)
- Ensure correct formatting of data
- Prevent incorrect or malicious values
- Improve application reliability
Instead of manually looping through characters, JavaScript provides efficient ways to handle these checks.
Real-world use cases
Some common real-life scenarios include:
- Validation: Checking if a filename ends with
.jpgor.pdf - Parsing: Verifying if a URL starts with
https:// - Filters: Identifying strings that start with a specific prefix like
EMP_ - Security: Blocking inputs that start or end with restricted characters
What Does “Starts and Ends With Certain Characters” Mean?
When we say a string starts with certain characters, it means those characters appear at the beginning of the string.
Similarly, ends with means the characters appear at the end of the string.
Simple explanation with examples
"JavaScript".startsWith("Java"); // true
"JavaScript".endsWith("Script"); // true
Here:
"Java"is the prefix"Script"is the suffix
Common scenarios (prefix and suffix checks)
- Prefix check:
"INV_1023"starts with"INV_" - Suffix check:
"photo.png"ends with".png" - Both start and end check:
"@username@"starts and ends with"@"
JavaScript Program to Check String Starts and Ends (Basic Logic)
Before ES6 methods existed, developers used basic string logic to solve this problem. Let’s understand those approaches.
Using charAt()
let str = "Hello!";
let startChar = 'H';
let endChar = '!';
if (str.charAt(0) === startChar && str.charAt(str.length - 1) === endChar) {
console.log("String starts and ends with given characters");
} else {
console.log("Condition not satisfied");
}
Explanation:
charAt(0)checks the first characterstr.length - 1gets the last character
Using string length comparison
let str = "WelcomeHome";
let start = "Welcome";
let end = "Home";
if (
str.substring(0, start.length) === start &&
str.substring(str.length - end.length) === end
) {
console.log("String starts and ends correctly");
} else {
console.log("Check failed");
}
This method is useful when checking multiple characters, not just one.
Using startsWith() and endsWith() (Recommended ES6 Method)
Modern JavaScript provides built-in methods that make this task easier and more readable.
Syntax explanation
string.startsWith(searchString) string.endsWith(searchString)
- Returns
trueif the condition matches - Otherwise returns
false
Example program
let str = "JavaScript Program";
if (str.startsWith("Java") && str.endsWith("Program")) {
console.log("String starts and ends with specified characters");
} else {
console.log("Condition not met");
}
✅ Clean
✅ Readable
✅ Beginner-friendly
Case sensitivity note
Both startsWith() and endsWith() are case-sensitive.
"Hello".startsWith("hello"); // false
To avoid issues, convert the string first:
str.toLowerCase().startsWith("java");
JavaScript Program Using User Input
In real applications, strings and characters usually come from user input, not hardcoded values. Let’s see how to handle dynamic input properly.
Checking dynamic strings
let str = prompt("Enter a string:");
let start = prompt("Enter starting characters:");
let end = prompt("Enter ending characters:");
if (str.startsWith(start) && str.endsWith(end)) {
console.log("String starts and ends with the given characters");
} else {
console.log("String does not match the condition");
}
How it works:
- Takes string input dynamically
- Uses
startsWith()andendsWith()for clean validation - Works for both single and multiple characters
Handling multiple characters
let str = "INV_2026_REPORT"; let startChars = "INV_"; let endChars = "_REPORT"; let result = str.startsWith(startChars) && str.endsWith(endChars); console.log(result); // true
This approach is commonly used for:
- File naming conventions
- Employee IDs
- Invoice or order numbers
Edge Cases to Consider
Ignoring edge cases can cause unexpected errors or incorrect results.
Empty strings
let str = "";
console.log(str.startsWith("A")); // false
console.log(str.endsWith("Z")); // false
Always check if the string is empty before validation.
Single-character strings
let str = "A";
if (str.startsWith("A") && str.endsWith("A")) {
console.log("Valid single-character string");
}
This works fine, but index-based logic must be handled carefully.
Special characters & spaces
let str = " @hello@ ";
console.log(str.trim().startsWith("@"));
console.log(str.trim().endsWith("@"));
Use .trim() to remove unwanted spaces before checking.
Comparison of Different Approaches
| Method | Easy to Use | ES6 | Performance |
|---|---|---|---|
charAt() | Medium | ❌ | Good |
substring() | Medium | ❌ | Good |
startsWith() / endsWith() | ✅ Very Easy | ✅ | Excellent |
Recommendation:
Use startsWith() and endsWith() whenever ES6 support is available.
Common Mistakes to Avoid
Case mismatch
"JavaScript".startsWith("javascript"); // false
✅ Fix:
str.toLowerCase().startsWith("javascript");
Index errors
str.charAt(str.length); // ❌ wrong index
✅ Correct:
str.charAt(str.length - 1);
Ignoring input validation
// Bad practice str.startsWith(start);
✅ Better approach:
if (str && start && end) {
str.startsWith(start) && str.endsWith(end);
}
Real-Life Uses of JavaScript program to check string starts and ends
Let’s dive into some real-world scenarios where a ‘JavaScript program to check whether a string starts and ends with certain characters’ is practically applied. Here’s how companies or brands might utilize this JavaScript capability:
- URL Validation for Web Security:
Many organizations implement this JavaScript functionality to validate URLs. For instance, when users input URLs into a form, the program checks if they start with “https://” and end with a specific domain extension like “.com”. This ensures that users only enter secure and validated links, protecting both the user and company data. - Email Filtering:
Email service providers or companies use this approach to filter and categorize incoming emails. By checking if an email subject line starts with terms like “Urgent” or ends with “Action Required,” emails can be classified and prioritized effectively, helping employees focus on critical tasks without delay. - Brand Name Integrity:
Companies often monitor the use of their brand names across social media platforms. By employing JavaScript programs to verify that posts or tweets mentioning their brand start with the brand’s specific hashtags and end with designated promo codes, brands maintain consistency in marketing campaigns and uphold their image. - Log File Analysis:
IT departments use this function to assess server logs, making sure entries start and end with specific markers for easy identification. This helps in swiftly isolating issues or monitoring usage patterns, ensuring efficient operations.
Quiz: JavaScript program to check string starts and ends
1️⃣ What is the difference between startsWith() and indexOf() in JavaScript?
Although both can be used to check prefixes, they are not the same.
startsWith()checks only the beginning of the stringindexOf()searches the entire string
"JavaScript".indexOf("Java") === 0; // works, but not ideal
"JavaScript".startsWith("Java"); // recommended
✅ startsWith() is more readable, safer, and purpose-built.
2️⃣ Can I check if a string starts and ends with multiple possible values?
Yes, but JavaScript does not provide a built-in method for multiple values. You must use arrays.
let prefixes = ["http://", "https://"];
let suffixes = [".com", ".org"];
let str = "https://example.com";
let valid =
prefixes.some(p => str.startsWith(p)) &&
suffixes.some(s => str.endsWith(s));
console.log(valid); // true
This pattern is widely asked on Reddit but rarely explained properly.
3️⃣ Do startsWith() and endsWith() work in older browsers?
Not fully.
- Supported in modern browsers
- ❌ Not supported in Internet Explorer
Fallback solution:
str.substring(0, start.length) === start
If IE support is required, avoid ES6 methods or use polyfills.
4️⃣ Are startsWith() and endsWith() slower than manual string checks?
No. In fact:
- Performance difference is negligible
- Built-in methods are often optimized internally
For real-world applications, readability and maintainability matter more than micro-optimizations.
So always prefer:
str.startsWith("A") && str.endsWith("Z");
5️⃣ How do I ignore spaces and case while checking string start and end?
This is one of the most asked but least answered questions.
let str = " JavaScript ";
let result =
str.trim().toLowerCase().startsWith("java") &&
str.trim().toLowerCase().endsWith("script");
console.log(result); // true
✅ Use:
.trim()→ remove extra spaces.toLowerCase()→ avoid case mismatch
Welcome to the world of coding convenience with our AI-powered js online compiler! Imagine writing, running, and testing your JavaScript code instantly, all with the assistance of AI. It’s like having a smart coding buddy right by your side, making programming easier and more efficient.
Conclusion
Congrats! Embracing this technique empowers you to control string data efficiently. Crafting a JavaScript program to check whether a string starts and ends with certain characters boosts your problem-solving skills immensely. Ready to apply your new skills? Dive into more cool topics on Newtum, and feel the thrill of coding at your fingertips. Keep exploring and coding!
Edited and Compiled by:
This blog was compiled and edited by @rasikadeshpande, who has over 4 years of experience in writing. She’s passionate about helping beginners understand technical topics in a more interactive way.