Code Logo

Starts With

Published at24 Jul 2026
TypeScript String Handling Easy 0 views
Like0

Write a TypeScript function that checks if a string starts with a given prefix. Do not use the built-in startsWith() method — implement the logic manually.

If the prefix is longer than the string, return false. Loop through the prefix characters and compare with the corresponding characters in the string at the same positions. If all characters match, return true.

Edge cases include empty prefix (return true), empty string with non-empty prefix (return false), and case-sensitive comparison.

The prefix check algorithm compares characters one by one from the beginning. If any character mismatches, the function returns false immediately. This early exit optimization provides O(1) best-case performance when the first character differs.

TypeScript's boolean return type ensures the function always returns true or false. The length check at the beginning prevents out-of-bounds access when the prefix is longer than the text.

Edge cases include empty prefix (always returns true), empty string with non-empty prefix (returns false), and exact matches where the prefix equals the entire string.

The prefix check algorithm compares characters one by one from the beginning. If any character mismatches, the function returns false immediately. This early exit optimization provides O(1) best-case performance when the first character differs.

TypeScript's boolean return type ensures the function always returns true or false. The length check at the beginning prevents out-of-bounds access when the prefix is longer than the text.

Edge cases include empty prefix (always returns true), empty string with non-empty prefix (returns false), and exact matches where the prefix equals the entire string. The charAt() method is used for character comparison.

Example Input & Output

Example 1
Input
"hello", "hello"
Output
true
Example 2
Input
"hello", ""
Output
true
Example 3
Input
"hi", "hello"
Output
false
Example 4
Input
"hello", "he"
Output
true
Example 5
Input
"hello", "hi"
Output
false

Algorithm Flow

Recommendation Algorithm Flow for Starts With
Recommendation Algorithm Flow for Starts With

Solution Approach

If prefix.length > text.length, return false. Loop from 0 to prefix.length - 1. If text.charAt(i) !== prefix.charAt(i), return false. After the loop, return true.

The time complexity is O(m) where m is the prefix length. Space complexity is O(1).

Best Answers

typescript - Approach 1
function startsWith(text: string, prefix: string): boolean {
    if (prefix.length > text.length) return false;
    for (var i = 0; i < prefix.length; i++) {
        if (text.charAt(i) !== prefix.charAt(i)) return false;
    }
    return true;
}