Ecmascript 6 Features 12: Strings
Welcome to another ES6: Features post. I think I might be getting to the end of this series soon! Anyway, this week's post is going to be on the new string related additions that have been made in Ecmascript 6. First up is a neww utility method called
repeat(). As the name suggests, it duplicates a string a specified number of times:
> "e".repeat(10) 'eeeeeeeeee' > "=-".repeat(4) '=-=-=-=-' > "Precarious Porcupine".repeat(3) 'Precarious PorcupinePrecarious PorcupinePrecarious Porcupine'
No more abusing
new Array(length + 1).join(number)! It looks like one of those functions that should have been added a long time ago. As usual, the MDN has a polyfill that you can use.
Next up is a set of functions that make searching for things in strings much easier. There's
includes, and they all return a boolean:
"porcupine".startsWith("p"); // true "porcupine".startsWith("pine", 5); // true
startsWith has an optional second argument, which lets you specify an offset from which to begin searching.
endsWidth also has an optional second argument, but it lets you limit the number of characters that are searched:
"erroneous elephant".startsWith("waterfront"); // false "erroneous elephant".endsWith("neous"); // false "erroneous elephant".endsWith("neous", 9); // true
includes. It works as you might expect it to, with the optional second argument specifying the offset from which to search:
"catastrophic crocodile".includes("croc"); // true "catastrophic crocodile".includes("cat", 8); // false
This trio of functions should make complex string manipulation much easier to understand as you don't have to use any more complex
indexOf tests anymore.