Skip to content
Code with Hou

Learn Modern JavaScript - Strings

JavaScript, beginner, tutorial, learn-modern-javascript1 min read

Introduction

By the end of this tutorial, you will be able to:

  • use new ES6 string methods
  • apply the template literal syntax

Strings

ES6 strings offers new string methods, template literals, and tagged template literals.

New String Methods

ES6 offers a few new string methods:

  • .repeat(number): repeats a given string a specified number of time.
  • .startsWith(searchString, position): returns true if a string starts with searchString. The position parameter specifies the start position of the search, with the default value being 0.
  • .endsWith(searchString, length): returns true if a string ends with searchString. The length parameter specifies the length of the string to search.
  • .includes(searchString, position): returns true if a given string can be found in another string.

Template Literals

Template literals allow you to embed expressions in your strings using backticks (`) and ${express}`. It can help simplify the syntax string concatenation and creating multiline strings. For example:

1const greeting = "Good morning";
2const weather = "sunny";
3
4// ES5
5const sentence =
6 greeting + ", how are you doing?" + " The weather is " + weather + " today.";
7
8// ES6
9const sentenceES6 = `${greeting}, how are you doing? The weather is ${weather} today.`;
10
11const multiLineString = `
12Hello,
13my friend,
14how are you, doing?
15`;
16console.log(multiLineString);
17
18/* Outputs
19Hello,
20my friend,
21how are you, doing?
22*/

Want more content like this? Subscribe to get the latest updates in your inbox

Share your Feedback

What did you like or didn't like about this post? Let me know what worked well and what can be improved. Your feedback is much appreciated!