Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Strings

A string is text: a user's name, a page title, an error message. Strings appear in almost every program, so it is worth getting the basics right from the start.

Writing a string

A string is written in single or double quotes — there is no difference between them. The opening and closing quotes just have to match:

console.log('Hello, world!'); // Hello, world!

This tutorial uses single quotes, as many projects do.

Joining strings

The + operator joins strings into one. This operation is called concatenation:

console.log('Java' + 'Script'); // JavaScript

Spaces do not appear by themselves — you have to add them to one of the strings:

const name = 'Anna';
 
console.log('Hello, ' + name + '!'); // Hello, Anna!

Template literals

The third kind of quotes is the backtick (`). Inside backticks a value is inserted with ${...}, and the curly braces can hold any expression:

const price = 20;
 
console.log(`Total: $${price * 3}`); // Total: $60

Template literals read more easily than a chain of +, so they are the usual way to build text from parts.

Length and single characters

The number of characters is stored in the length property. A property is a value the string knows about itself, so there are no parentheses after it:

console.log('hello'.length); // 5

A single character is taken by its number in square brackets. That number is called an index, and counting starts at zero:

const word = 'hello';
 
console.log(word[0]);               // h
console.log(word[word.length - 1]); // o

Quotes inside a string

If the string needs the same quote as the one around it, put a backslash \ in front of it. It is simpler to use the other kind of quotes:

console.log('It\'s fine'); // It's fine
console.log("It's fine");  // It's fine

First methods

Strings have many built-in methods — functions you call with a dot. Here are the simplest:

console.log('hello'.toUpperCase());           // HELLO
console.log('HELLO'.toLowerCase());           // hello
console.log('Hello, world'.includes('world')); // true
console.log('  text  '.trim());               // text

includes() checks whether the string contains a fragment, and trim() removes spaces at both ends. The other methods are covered in the chapter on working with text.

Common mistake

A string cannot be changed "in place": methods return a new string, and the original stays the same. Save the result into a variable:

let text = 'hello';
text.toUpperCase();
console.log(text); // hello
 
text = text.toUpperCase();
console.log(text); // HELLO

Thanks for reading!

Donate to the site — we work hard for you.