This page looks best with JavaScript enabled

ES6 String Operations That Rock the World

 ·   ·  ☕ 2 min read

There are many great improvements provided by ES6 (introduced in Y2015), but I think a couple of them are really cool.

String includes

includes checks whether a certain (sub) string exists in the provided string. Note that this operation is case sensitive.

1
2
3
let str1 = "Neo rocks the world";
console.log("rocks? ", str1.includes("rocks")); // rocks?  true
console.log("is agent? ", str1.includes("agent")); // is agent?  false

Not quite complicated, but makes the language that much more friendly :)

Earlier, we used a very complicated piece of code to achieve the same result.

1
2
let str1 = "Neo rocks the world";
console.log("rocks? ", str1.indexOf("rocks") > 0); // rocks?  true

The same works for arrays as well.

1
2
3
let fruits = ["apple", "orange"];
console.log("keeps doctor away? ", fruits.includes("apple")); // keeps doctor away?  true
console.log("sour? ", !fruits.includes("grapes")); // sour?  true

String startsWith and endsWith

If you totally dig includes, but wanted that extra zing to find start or end variables - ES6 has you covered.

1
2
3
const statement = "javascript is totally awesome";
console.log("we love javascript - ", statement.startsWith("javascript")); // true
console.log("is it awesome?", statement.endsWith("awesome")); // true

String match

Regular expressions are a must if you have more complex requirements for a string search. We can do that in Javascript with just the string variable.

1
2
3
let str1 = "Neo rocks the world";
const match = str1.match(/world/gi);
console.log("rocks what? ", match); // [ 'world' ]

String repeat

How about repeating a string x number of times? Yes, totally possible.

1
2
const sayHello = "hello ";
console.log("echo:  ", sayHello.repeat(3)); // echo:   hello hello hello
Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things