ES6 in Action: New String Methods — String.prototype.*

Aurelio De Rosa
Share

In my previous article on ES6 array methods, I introduced the new methods available in ECMAScript 6 that work with the Array type. In this tutorial, you’ll learn about new ES6 methods that work with strings: String.prototype.*

We’ll develop several examples, and mention the polyfills available for them. Remember that if you want to polyfill them all using a single library, you can employ es6-shim by Paul Miller.

String.prototype.startsWith()

One of the most-used functions in every modern programming language is the one to verify if a string starts with a given substring. Before ES6, JavaScript had no such function, meaning you had to write it yourself. The following code shows how developers usually polyfilled it:

if (typeof String.prototype.startsWith !== 'function') {
  String.prototype.startsWith = function (str){
    return this.indexOf(str) === 0;
  };
}

Or, alternatively:

if (typeof String.prototype.startsWith !== 'function') {
  String.prototype.startsWith = function (str){
    return this.substring(0, str.length) === str;
  };
}

These snippets are still valid, but they don’t reproduce exactly what the newly available String.prototype.startsWith() method does. The new method has the following syntax:

String.prototype.startsWith(searchString[, position]);

You can see that, in addition to a substring, it accepts a second argument. The searchString parameter specifies the substring you want to verify is the start of the string. position indicates the position at which to start the search. The default value of position is 0. The methods returns true if the string starts with the provided substring, and false otherwise. Remember that the method is case sensitive, so “Hello” is different from “hello”.

An example use of this method is shown below:

const str = 'hello!';
let result = str.startsWith('he');

// prints "true"
console.log(result);

// verify starting from the third character
result = str.startsWith('ll', 2);

// prints "true"
console.log(result);

A live demo of the previous code is shown below and also available at JSBin.

ES6 in Action: New String Methods on jsbin.com

The method is supported in Node and all modern browsers, with the exception of Internet Explorer. If you need to support older browsers, a polyfill for this method can be found in the method’s page on MDN. Another polyfill has also been developed by Mathias Bynens.

String.prototype.endsWith()

In addition to String.prototype.startsWith(), ECMAScript 6 introduces the String.prototype.endsWith() method. It verifies that a string terminates with a given substring. The syntax of this method, shown below, is very similar to String.prototype.startsWith():

String.prototype.endsWith(searchString[, position]);

As you can see, this method accepts the same parameters as String.prototype.startsWith(), and also returns the same type of values.

A difference is that the position parameter lets you search within the string as if the string were only this long. In other words, if we have the string house and we call the method with 'house'.endsWith('us', 4), we obtain true, because it’s like we actually had the string hous (note the missing “e”).

An example use of this method is shown below:

const str = 'hello!';
const result = str.endsWith('lo!');

// prints "true"
console.log(result);

// verify as if the string was "hell"
result = str.endsWith('lo!', 5);

// prints "false"
console.log(result);

A live demo of the previous snippet is shown below and is also available at JSBin.

ES6 in Action: New String Methods on jsbin.com

The method is supported in Node and all modern browsers, with the exception of Internet Explorer. If you need to support older browsers, a polyfill for this method can be found in the method’s page on MDN. Another polyfill has been developed by Mathias Bynens.

String.prototype.includes()

While we’re talking about verifying if one string is contained in another, let me introduce you to the String.prototype.includes() method. It returns true if a string is contained in another, no matter where, and false otherwise.

Its syntax is shown below:

String.prototype.includes(searchString[, position]);

The meaning of the parameters is the same as for String.prototype.startsWith(), so I won’t repeat them. An example use of this method is shown below:

const str = 'Hello everybody, my name is Aurelio De Rosa.';
let result = str.includes('Aurelio');

// prints "true"
console.log(result);

result = str.includes('Hello', 10);

// prints "false"
console.log(result);

You can find a live demo below and also as at JSBin.

ES6 in Action: New String Methods on jsbin.com

String.prototype.includes() is supported in Node and all modern browsers, with the exception of Internet Explorer. If you need to support older browsers, as with the other methods discussed in this tutorial, you can find a polyfill provided by Mathias Bynens (this guy knows how to do his job!) and another on the Mozilla Developer Network.

Note: until version 48, Firefox uses the non-standard name contains.

String.prototype.repeat()

Let’s now move on to another type of method. String.prototype.repeat() is a method that returns a new string containing the same string it was called upon but repeated a specified number of times. The syntax of this method is the following:

String.prototype.repeat(times);

The times parameter indicates the number of times the string must be repeated. If you pass zero you’ll obtain an empty string, while if you pass a negative number or infinity you’ll obtain a RangeError.

An example use of this method is shown below:

const str = 'hello';
let result = str.repeat(3);

// prints "hellohellohello"
console.log(result);

result = str.repeat(0);

// prints ""
console.log(result);

A live demo of the previous code is shown below and is also available at JSBin.

ES6 in Action: New String Methods on jsbin.com

The method is supported in Node and all modern browsers, with the exception of Internet Explorer. If you need to support older browsers, two polyfills are available for this method: the one developed by Mathias Bynens and another on the Mozilla Developer Network.

String.raw()

The last method I want to cover in this tutorial is String.raw(). It’s defined as a tag function of template strings. It’s interesting, because it’s kind of a replacement for templating libraries, although I’m not 100% sure it can scale enough to actually replace those libraries. However, the idea is basically the same as we’ll see shortly. What it does is to compile a string and replace every placeholder with a provided value.

Its syntax is the following (note the backticks):

String.raw`templateString`

The templateString parameter represents the string containing the template to process.

To better understand this concept, let’s see a concrete example:

const name = 'Aurelio De Rosa';
const result = String.raw`Hello, my name is ${name}`;

// prints "Hello, my name is Aurelio De Rosa" because ${name}
// has been replaced with the value of the name variable
console.log(result);

A live demo of the previous code is shown below and is also available at JSBin.

ES6 in Action: New String Methods on jsbin.com

The method is supported in Node and all modern browsers, with the exception of Opera and Internet Explorer. If you need to support older browsers, you can employ a polyfill, such as this one available on npm.

Conclusion

In this tutorial, you’ve learned about several new methods introduced in ECMAScript 6 that work with strings. Other methods that we haven’t covered are String.fromCodePoint(), String.prototype.codePointAt(), and String.prototype.normalize(). I hope you enjoyed the article and that you’ll continue to follow our channel to learn more about ECMAScript 6.