New String Features

New String Features

Strings are iterable collections

String data type became an iterable collection of data from the ES2015 standard. “iterables”. Strings are now accessible by all mechanisms that require the collection to have the “iterable protocol” implemented. So now we can use “for..of” over strings:

or even use the spread operator which also requires an iterable collection to create an array:

See more about this in “Iterators and the Iterable Protocol”

Template literals

template literals

Template literals (eng. “template literals”) are character strings (so-called strings) with built-in expressions. They are marked with backtick.
“Template literal” represents a new improved way of string concatenation, which is more transparent and easier to work with. Expressions are allowed to be embedded in the template literal, if they are marked with a dollar sign and curly brackets. The template includes the so-called ” “preset format” while “literal” represents a value that is written exactly as it is intended to be interpreted. Therefore, every newline, extra space (tab) becomes part of that string
Template literals combine the following characteristics:

  • String interpolation
  • Multi-line string literals so called. “preset format”, ie. how it is written in the code is how it is interpreted at the output.
Example

Example done with ES5 and string concatenation:

New approach with template literals:

New string methods

String.startsWith()

This method checks if the string starts with the specified character set, if it does then returns “True”:

Or with an additional optional parameter defining the place:

String.endsWith()

This method checks if the string ends with the specified set of characters, if it does then returns “True”:

Or with an additional optional parameter defining the place:

String.include()

This method checks if the string contains a certain set of characters, if it does then returns “True”:

Or with an additional optional parameter defining the place:

String.repeat()

This method returns the selected string incremented by the desired number of times.

String.fromCodePoint()

This method returns a string of the specified numeric value.

See Online Unicode text converter, while the codes of each keycode can be viewed here.

String.codePointAt()

Returns a numeric value from the member at the specified position