Exercise 18: Check if String Starts with Substring
Problem Statement
Function `startsWith(str, prefix)` banao jo check kare ki string prefix se start hoti hai ya nahi (case-insensitive).
Example:
- startsWith("Hello", "he") → true
- startsWith("World", "he") → false
Sample Output:
startsWith("Hello", "he") => true
startsWith("World", "he") => falseSolution
const startsWith = (str, prefix) => {
const s = String(str ?? "").toLowerCase();
const p = String(prefix ?? "").toLowerCase();
return s.startsWith(p);
};Explanation
Overall Goal:
- String prefix se start hoti hai ya nahi check karna.
Line 1: Function header
const startsWith = (str, prefix) => {
Line 2-3: Normalize
- Lowercase me convert.
Line 4: Check
return s.startsWith(p);
Real world:
- String matching: prefix checks.
- Validation: prefix validation.