JavaScript
Article
By Aurelio De Rosa

Preparing for ECMAScript 6: New String Methods

By Aurelio De Rosa

In my previous article, I introduced you to most of the new methods available in ECMAScript 6 “Harmony” that work with the Array type. In this tutorial you’ll learn about those that work with strings. 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. So far, JavaScript hasn’t had such a function, so 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 usage of this method is shown below:

var str = 'hello!';
var 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 as a JSFiddle.

The method is supported by Firefox 17+, and Chrome 35+ and Opera 22+ behind a flag (“Enable Experimental JavaScript”). 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 in this way '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:

var str = 'hello!';
var 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 also available as a JSFiddle.

The method is supported by Firefox 17+, and Chrome 35+ and Opera 22+ behind a flag (“Enable Experimental JavaScript”). 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:

var str = 'Hello everybody, my name is Aurelio De Rosa.';
var 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 a JSFiddle.

String.prototype.includes() is currently supported by Firefox 17+, and Chrome 35+ and Opera 22+ behind the usual flag. Just like 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.

--ADVERTISEMENT--

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:

var str = 'hello';
var 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 also available as a JSFiddle.

This method is supported by Firefox 24+, and Chrome 35+ and Opera 22+ behind the usual flag. Two polyfills for this method are 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 its 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 in a moment. 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:

var name = 'Aurelio De Rosa';
var 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);

Unfortunately at the time of this writing, String.raw isn’t supported by any browser. For this reason, I’m not including a demo for it.

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.

Recommended
Sponsors
The most important and interesting stories in tech. Straight to your inbox, daily. Get Versioning.
Login or Create Account to Comment
Login Create Account