New ES6 string methods

Photo by Andrew Neel on Unsplash

New ES6 string methods

Table of contents

No heading

No headings in the article.

ES6 introduced new string methods such as startsWith(), endsWith(), includes(), padStart(), padEnd(), repeat().

  • To check if a string starts with a specified substring, use startsWith() .

    It returns true or false

      console.log("Atlanta, Ga".startsWith("Atl")) // true
      console.log("Atlanta, Ga".startsWith("Ga")) // false
      console.log("Atlanta, Ga".startsWith("Ga", 14)); // false
      console.log("Atlanta, Ga".startsWith("Ga", 9)) //true

    This method accepts an optional second parameter to specify the position in the string to start searching.

  • To check if a string ends with a specified substring, use endsWith() It returns true or false.

      console.log("Atlanta, Ga".endsWith("Atl")) // false
      console.log("Atlanta, Ga".endsWith("Ga")) // true
      console.log("Atlanta, Ga".endsWith("Ga", 10)) //false
      console.log("Atlanta, Ga".endsWith("Ga", 11)) //true

    This method accepts an optional second parameter (length), which is the length of the string to consider for the search. If provided, only the characters within the specified length are considered. If not provided, the entire string is considered.

  • To check whether a string contains a substring, use includes(). It returns true or false.

      console.log("Atlanta, Ga".includes("lan")); //true
      console.log("Atlanta, Ga".includes("Lan")); //false
      console.log("Atlanta, Ga".includes("lan", 10)); //false
      console.log("Atlanta, Ga".includes("lan", 2)); //true

All of the above three methods perform a case-sensitive search.

The next two string methods padStart() and padEnd() accepts two arguments: the max length of the returned string, and the filler string:

  • To pad the start of a string, use padStart()

      console.log("Alice".padStart(10, "Bob ")); // Bob Alice
      console.log("def".padStart(6, "abc")); // abcdef
  • To pad the end of a string, use padEnd()

      console.log("abcd".padEnd(7, "efg")) // abcdefg

    If the filler is multiple chars and can’t evenly be added, it will be truncated:

      console.log("Hello".padEnd(10, "all")); // Helloallal

    If the max length is less than the original string’s length, the original string will be returned without any padding applied:

      console.log("Hello, World".padEnd(10, "!!!")) // Hello, World
  • To repeat a string a given number of times, use repeat()

      console.log("no".repeat(3)) // nonono

These are just a few of the new string methods introduced in ES6. They provide convenient ways to perform common string operations and manipulate strings in JavaScript. They are not only consistent but much easier to understand exactly what they’re doing at a glance.