ES6 Everyday: New String Methods

Let’s end the week with an easy topic: some handy new String methods in ES6.

String.prototype.repeat()

console.log("bum ".repeat(3)); // "bum bum bum"

MDN: String.prototype.repeat() and a ES6 Fiddle.

String.prototype.startsWith()

var quote = "Toto, I've a feeling we're not in Kansas anymore.";
console.log(quote.startsWith("Toto")); // true
console.log(quote.startsWith("feeling")); // false

There’s an optional position parameter that can be used to control which position is considered the start of the string:

var quote = "Toto, I've a feeling we're not in Kansas anymore."
console.log(quote.startsWith("feeling", 13)); // true

MDN: String.prototype.startsWith() and a ES6 Fiddle.

String.prototype.endsWith()

var quote = "I'm going to make him an offer he can't refuse";
console.log(quote.endsWith("refuse")); // true
console.log(quote.endsWith("offer")); // false

As with startsWith, there’s a position parameter to control which position is considered the end of the string:

var quote = "I'm going to make him an offer he can't refuse";
console.log(quote.endsWith("offer", 30)); // true

MDN: String.prototype.endsWith() and a ES6 Fiddle.

String.prototype.includes()

I know it’s small, but I’m really excited about this one:

var quote = "Go ahead, make my day.";
console.log(quote.includes('ahead')); // true
console.log(quote.includes('night')); // false

That’s right, no more indexOf nonsense!

There’s also an optional position parameter here, that behaves the same as the startsWith position parameter:

var quote = "Go ahead, make my day.";
console.log(quote.includes('ahead', 10)); // false

MDN: String.prototype.includes() and a ES6 Fiddle.