Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Return TRUE if the first string starts with a specific second string JavaScript
We are required to write a JavaScript function that takes in two strings and checks whether the first string starts with the second string or not.
For example:
If the two strings are: "Disaster management report" "Disas" Then our function should return true
There are multiple ways to check if a string starts with another string in JavaScript. Let's explore the most common approaches.
Using startsWith() Method (Recommended)
The startsWith() method is the built-in and most straightforward way to check if a string starts with another string:
const first = 'The game is on';
const second = 'The';
console.log(first.startsWith(second));
console.log('Disaster management report'.startsWith('Disas'));
console.log('Hello World'.startsWith('Hi'));
true true false
Custom Implementation Using substr()
Here's how to implement the functionality manually using substr():
const first = 'The game is on';
const second = 'The';
const startsWith = (first, second) => {
const { length } = second;
const sub = first.substr(0, length);
return sub === second;
};
console.log(startsWith(first, second));
console.log(startsWith('JavaScript Tutorial', 'Java'));
true true
Using substring() Method
Another approach using substring() method:
const checkStartsWith = (str, prefix) => {
return str.substring(0, prefix.length) === prefix;
};
console.log(checkStartsWith('Hello World', 'Hello'));
console.log(checkStartsWith('Programming', 'Code'));
true false
Comparison of Methods
| Method | Browser Support | Performance | Readability |
|---|---|---|---|
startsWith() |
ES6+ | Best | Excellent |
substr() |
All browsers | Good | Good |
substring() |
All browsers | Good | Good |
Case-Sensitive vs Case-Insensitive
By default, all methods are case-sensitive. For case-insensitive comparison:
const str = 'Hello World'; const prefix = 'hello'; // Case-sensitive (default) console.log(str.startsWith(prefix)); // Case-insensitive console.log(str.toLowerCase().startsWith(prefix.toLowerCase()));
false true
Conclusion
Use the built-in startsWith() method for modern applications as it's the most readable and efficient. For older browser support, implement a custom solution using substr() or substring().
