W3docs

es6 · ES6 Basics

ES6 gives you a number of new methods for operating with Strings. Which one replaces this annoying piece of code?

let some_text = "some string"; 
if(some_text.indexOf('str') !=-1){
 return true;
 }

Answers

  • some_text.repeat('str');
  • some_text.endsWith('str');
  • some_text.includes('str');
# Understanding and Working with ES6 String Methods in JavaScript In JavaScript, ES6 (also known as ECMAScript 2015) introduced a range of new and simplified methods for string manipulation. The question above particularly refers to the replacement of a common JavaScript operation: checking if a specific string is present within another string. Before ES6, developers had to use `indexOf()`. This method returns the index of where the substring starts in the string, or -1 if the string is not found. This often resulted in code like the following: ```javascript let some_text = "some string"; if(some_text.indexOf('str') != -1){ return true; } ``` This piece of code is checking if 'str' exists in `some_text`. If `indexOf()` does not return -1, it means 'str' exists in `some_text`, hence `true` is returned. Although it works perfectly fine, ES6 introduced a more readable and intuitive method for this kind of operation: `includes()`. ## Usage of `includes()` The correct answer to the question is `some_text.includes('str');`. The `includes()` method simply checks if the string includes the specified string or not. It returns a boolean value — `true` if the string is found, and `false` if not. Here is how you can use it: ```javascript let some_text = "some string"; console.log(some_text.includes('str')); // Outputs: true ``` With `includes()`, the code becomes much more readable, especially to people new to JavaScript. The method clearly states its purpose, making the code easier to understand without needing comments. ## Best Practices and Additional Insights It is always good to utilize new methods and syntax that come with updates to a language. This not only makes your code more readable but also keeps it up-to-date with modern standards. It's also important to understand the difference between `includes()` and other similar string methods in ES6 like `startsWith()` and `endsWith()`. These are not interchangeable and each serves a different purpose. `startsWith()` checks if the string begins with specified characters, while `endsWith()` checks if the string ends with specified characters. So, understanding each of these methods and their unique functionalities is key to efficient and effective string operation in JavaScript. Similarly, `repeat()` is another ES6 method that isn't interchangeable with the above three. It returns a new string which is an existing string repeated a certain number of times. So in conclusion, `includes()` is an ES6 string method that simplifies checking if a string includes a specific substring, making the code tidier and more intuitive.