Are you an Indian fresher or student eyeing that dream job with a ₹12LPA+ package at a top company like Google India, Infosys SP, or a buzzing Bangalore/Hyderabad startup? Gearing up for TCS NQT 2026? Then you know that strong fundamentals are non-negotiable. One such crucial skill, frequently tested in coding interviews, is efficient string manipulation – specifically, checking if a string contains a particular substring in JavaScript.
At DevLingo, India’s premier gamified coding app, we empower thousands of students like you to crack these challenges. Let’s dive deep into the various JavaScript methods you can use to answer this common interview question confidently.
Why String Manipulation Matters for Your Dream Job From parsing user input forms to searching through massive datasets or implementing complex UI components, string operations are at the heart of almost every application. A strong grasp of how to efficiently search within strings is a testament to your problem-solving skills and your readiness for real-world development challenges. Interviewers at companies like Google and Flipkart often look for candidates who not only know *how* to solve a problem but also *why* a particular solution is optimal.
Method 1: The Modern & Recommended Approach: `String.prototype.includes()` Introduced in ES6 (ECMAScript 2015), the `includes()` method is arguably the most straightforward and readable way to check for a substring. It returns a simple boolean (`true` or `false`), making your code clean and intuitive.
Syntax: - `string.includes(searchString, position)` - `searchString`: The string to search for. - `position` (Optional): The position within the string at which to begin searching. Defaults to 0.
Example: ```javascript const mainString = 'DevLingo makes coding fun and easy!'; const substring1 = 'coding'; const substring2 = 'placement';
console.log(mainString.includes(substring1)); // Output: true console.log(mainString.includes(substring2)); // Output: false console.log(mainString.includes('fun', 10)); // Output: true (starts searching from index 10) console.log(mainString.includes('fun', 20)); // Output: false (not found after index 20) ```
Handling Case Sensitivity: A common pitfall! `includes()` is case-sensitive. If you need a case-insensitive check, convert both the main string and the substring to the same case (e.g., lowercase) before comparing.
```javascript const message = 'Hello World'; console.log(message.includes('world')); // Output: false (due to 'W' vs 'w') console.log(message.toLowerCase().includes('world')); // Output: true ```
Method 2: For Specific Index Needs: `String.prototype.indexOf()` Before `includes()`, `indexOf()` was the go-to method. It returns the index of the first occurrence of the specified substring within the calling string, or `-1` if the substring is not found. While `includes()` is simpler for a boolean check, `indexOf()` is useful when you also need to know *where* the substring is located.
Syntax: - `string.indexOf(searchString, position)` - Parameters are identical to `includes()`.
Example: ```javascript const interviewQuestion = 'How to check if a string contains a substring?'; const target = 'contains'; const notFound = 'array';
console.log(interviewQuestion.indexOf(target)); // Output: 24 (index of 'c' in 'contains') console.log(interviewQuestion.indexOf(notFound)); // Output: -1
if (interviewQuestion.indexOf(target) !== -1) { console.log('Substring found!'); } else { console.log('Substring not found.'); } ```
Handling Case Sensitivity with `indexOf()`: Like `includes()`, `indexOf()` is also case-sensitive. Apply the same `toLowerCase()` (or `toUpperCase()`) strategy for case-insensitive comparisons.
Method 3: Regular Expressions with `String.prototype.match()` or `RegExp.prototype.test()` For more complex pattern matching, regular expressions (regex) are incredibly powerful. They allow you to define intricate search patterns, making them suitable for scenarios where a simple substring check isn't enough (e.g., finding all email addresses, validating phone numbers, or searching for words that start with a certain letter and end with another).
Using `RegExp.prototype.test()` The `test()` method of a regular expression object is perfect for a boolean check. It returns `true` if the pattern exists in the string, otherwise `false`.
Example with `test()`: ```javascript const codeSnippet = 'DevLingo helps you ace your SDE-1 role.'; const regex1 = /SDE-1/; const regex2 = /java/i; // 'i' flag for case-insensitive matching const regex3 = /python/;
console.log(regex1.test(codeSnippet)); // Output: true console.log(regex2.test(codeSnippet)); // Output: false (even with 'i' flag, 'java' isn't there) console.log(/sde-1/i.test(codeSnippet)); // Output: true (case-insensitive check) ```
Using `String.prototype.match()` The `match()` method returns an array of all matches (including capturing groups) or `null` if no matches are found. It's useful when you need to extract the matched substrings themselves.
Example with `match()`: ```javascript const projectDescription = 'We are building a product for Bangalore startups (BLR).'; const regex = /(Bangalore|BLR)/g; // 'g' flag for global search (find all occurrences)
console.log(projectDescription.match(regex)); // Output: ['Bangalore', 'BLR'] console.log(projectDescription.match(/Hyderabad/)); // Output: null
if (projectDescription.match(/startup/)) { console.log('Found startup mention!'); } ```
Choosing the Right Method: DevLingo's Expert Advice Deciding which method to use depends on your specific needs and the complexity of the search.
- **`String.prototype.includes()`**:
- **Best for**: Simple, direct boolean checks ("does this string contain that substring?").
- **Readability**: Highest.
- **Performance**: Generally good for simple checks.
- **Interview Tip**: Your go-to for basic checks unless the question explicitly asks for index or complex patterns.
- **`String.prototype.indexOf()`**:
- **Best for**: When you need to know the *starting position* of the substring, or when working with older JavaScript environments (though ES6 is now widely supported).
- **Readability**: Good, but requires `!== -1` for a boolean check.
- **Performance**: Similar to `includes()` for simple checks.
- **Interview Tip**: Demonstrates understanding of older methods, useful for specific indexing problems.
- **Regular Expressions (`RegExp.prototype.test()` or `String.prototype.match()`)**:
- **Best for**: Complex pattern matching, case-insensitive searches without manual case conversion, finding multiple occurrences, or matching specific formats (e.g., email, dates).
- **Readability**: Can be lower for complex regex patterns.
- **Performance**: Can be slower for very simple checks but highly efficient for complex patterns.
- **Interview Tip**: Showcases advanced pattern matching skills, crucial for roles requiring data parsing or validation.
Practice Makes Perfect: Your Path to ₹12LPA+ Understanding these methods theoretically is just the first step. To truly ace your TCS NQT, Infosys SP, or Google India SDE-1 interviews and land that lucrative role in a top startup, consistent practice is key. Apply these concepts to various coding challenges. DevLingo offers a gamified learning path with hundreds of JavaScript problems to hone your skills and prepare you for real interview scenarios.
Ready to boost your Placement Prep 2026? Join DevLingo today and turn complex concepts into easy wins!
Frequently Asked Questions
How does this appear in interviews?
Interviewers frequently embed substring checks within larger problems. For instance, you might be asked to 'Implement a simple search bar functionality that highlights keywords in a given text' or 'Validate user input fields for specific keywords.' Beyond direct questions like 'Explain how `includes()` works,' you could face algorithm challenges where string searching is a core component, like 'Find the first non-repeating character in a string' or 'Implement `strStr()` (finding a needle in a haystack)'. Being familiar with the time complexity of these methods (often O(n*m) in the worst case, where n is main string length and m is substring length, but optimized in modern engines) is also a plus for senior roles.
Common mistake?
One of the most frequent mistakes is overlooking **case sensitivity**. Both `includes()` and `indexOf()` are case-sensitive by default. Forgetting to normalize the case (e.g., using `toLowerCase()`) when a case-insensitive search is required can lead to bugs or incorrect solutions. Another common pitfall with `indexOf()` is incorrectly interpreting its return value: `0` is a valid index meaning the substring is found at the very beginning, but some beginners might mistake it for `false` if they are not careful with `if (string.indexOf(sub) === -1)` checks. Always remember `0` is 'truthy' in JavaScript, so `if (string.indexOf(sub))` without `!== -1` could lead to errors.
