JavaScript - How to Check if a String "StartsWith" Another String in JavaScript?
Last Updated :
03 Dec, 2024
Here are the various methods to check if a string starts with another string in JavaScript
1. Using String.startsWith() Method
The most widely used method is the startsWith() method, built into JavaScript. This method is simple to use, highly readable, and performs the task efficiently.
JavaScript
let s = 'Hello World';
let pre = 'Hello';
if (s.startsWith(pre)) {
console.log(`The string starts with "${pre}"`);
} else {
console.log(`The string does not start with "${pre}"`);
}
OutputThe string starts with "Hello"
- startsWith() checks if the string begins with the substring prefix.
- It returns true if the condition is met, otherwise false.
- This method is case-sensitive and takes an optional second parameter to specify the position in the string to start the search.
2. Using String.slice() Method
If you're working with older versions of JavaScript or need to perform additional manipulation, slice() can also be used to extract the beginning of a string and compare it to a target substring.
JavaScript
let s = 'Hello World';
let prefix = 'Hello';
if (s.slice(0, prefix.length) === prefix) {
console.log(`The string starts with "${prefix}"`);
} else {
console.log(`The string does not start with "${prefix}"`);
}
OutputThe string starts with "Hello"
- slice(0, prefix.length) extracts the portion of the string from the start (0) to the length of the prefix.
- If the extracted portion matches the prefix, it confirms that the string starts with that substring.
3. Using String.indexOf() Method
Another approach is to use indexOf(), which returns the position of the first occurrence of the specified substring. If the index is 0, it indicates that the string starts with the given substring.
JavaScript
let s = 'Hello World';
let prefix = 'Hello';
if (s.indexOf(prefix) === 0) {
console.log(`The string starts with "${prefix}"`);
} else {
console.log(`The string does not start with "${prefix}"`);
}
- indexOf() returns 0 if the substring is found at the start of the string.
- This method works well but may be less used compared to startsWith().
4. Using String.substr() Method
You can also use the substr() method to extract a portion of the string and compare it to the desired substring. While this method is deprecated in some environments, it still works in most modern browsers.
JavaScript
let s = 'Hello World';
let prefix = 'Hello';
if (s.substr(0, prefix.length) === prefix) {
console.log(`The string starts with "${prefix}"`);
} else {
console.log(`The string does not start with "${prefix}"`);
}
- substr(0, prefix.length) extracts the first prefix.length characters from the string.
- The extracted portion is compared with the prefix to check if the string starts with it.
Which Approach to Choose?
Method | When to Use | Why Choose It |
---|
startsWith() | For modern JavaScript, most cases, and readability. | Simple, efficient, and built-in method for checking prefixes. |
slice() | When working with environments that don't support startsWith(). | Offers flexibility in manipulating and comparing string portions. |
indexOf() | For backward compatibility or when already familiar with the method. | Works well but less intuitive than startsWith() for prefix checks. |
substr() | When dealing with legacy code or old JavaScript versions. | Useful but now deprecated in favor of slice() or substring(). |
The startsWith() method is the simplest and most efficient solution for modern JavaScript. If you're working with older versions of JavaScript or need to manipulate the string in other ways, alternatives like slice(), indexOf(), and substr() are still valid options, though they may require more lines of code and less intuitive logic.
Similar Reads
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
JavaScript Interview Questions and Answers JavaScript is the most used programming language for developing websites, web servers, mobile applications, and many other platforms. In Both Front-end and Back-end Interviews, JavaScript was asked, and its difficulty depends upon the on your profile and company. Here, we compiled 70+ JS Interview q
15+ min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read