Working with Strings

Strings are something you'll work with a lot in JavaScript. We only touched off them briefly in the Primitive Data Types section, so we should look at them in more depth.

Strings represent sequences of characters and are used to handle text. This section will cover how to create strings, get their length, access individual characters, use template literals, and perform various operations on them.

What is a String?

A string is a sequence of characters enclosed in single quotes ('), double quotes ("), or backticks (`).

const greeting = 'Hello, World!';
const quote = "JavaScript is fun.";
const template = `This is a template literal.`;

Now that we have covered Arrays and you have seen how they work and have magic properties and indexes, you'll see that strings are similar.

Getting the Length of a String

You can get the length of a string using the length property. This tells you how many characters are in the string.

Example:

let message = 'Hello, World!';
console.log(message.length); // Outputs: 13

Accessing Individual Characters

Strings, like arrays, have indices that start at 0. You can access individual characters in a string using bracket notation with the character index you want to access.

let message = 'Hello, World!';
console.log(message[0]); // Outputs: H
console.log(message[1]); // Outputs: e
console.log(message[7]); // Outputs: W

Like arrays, the first character is at index 0; the second character is at index 1, and so on.

Combining Strings

Often, you'll want to join strings together. You can combine or concatenate strings using the + operator or the concat() method.

Using the + operator:

const firstName = 'Alice';
const lastName = 'Smith';
const fullName = firstName + ' ' + lastName;
console.log(fullName); // Outputs: Alice Smith

Using the concat() method:

const firstName = 'Alice';
const lastName = 'Smith';
const fullName = firstName.concat(' ', lastName);
console.log(fullName); // Outputs: Alice Smith

We will look at some other magic methods like concat() a little later.

Template Literals

So I've been calling those strings created with ` "strings," and they work mostly the same with a few more superpowers.

They are "template literals," a special type of string because they can do a few things that other strings can't, such as:

  1. Embedded Expressions: You can include variables and expressions inside a template literal using ${}.
  2. Multi-line Strings: Template literals can span multiple lines without needing special characters.

Embedded Expressions:

const name = 'Alice';
const greeting = `Hello, ${name}!`; // Embeds the value of 'name' into the string
console.log(greeting); // Outputs: Hello, Alice!

const stringWithMath = `The number is: ${2 + 2}`; 
console.log(stringWithMath); // Outputs: The number is: 4

Multi-line Strings:

let poem = `Roses are red,
Violets are blue,
JavaScript is fun,
And so are you.`;
console.log(poem);
// Outputs:
// Roses are red,
// Violets are blue,
// JavaScript is fun,
// And so are you.

Handling Special Characters

I mentioned above that string templates handle newlines without special characters. But what are they?

As another example, what if you wanted to add the character " inside a string you created with ""?

Sometimes, you must include special characters in your strings, such as quotes, backslashes, or newlines. You can do this using escape sequences.

Escape sequences are combinations of characters that represent special characters in a string. They allow you to include otherwise difficult characters to type directly into a string.

Here are some of the common ones you might need:

  • Newline (\n): Adds a new line within the string.
  • Backslash (\\): Adds a backslash character.
  • Single Quote (\'): Adds a single quote within a single-quoted string.
  • Double Quote (\"): Adds a double quote within a double-quoted string.

Newline:

let message = 'Hello,\nWorld!';
console.log(message);
// Outputs:
// Hello,
// World!

Backslash:

let path = 'C:\\Program Files\\MyApp';
console.log(path); // Outputs: C:\Program Files\MyApp

Single Quote and Double Quote:

let singleQuote = 'It\'s a beautiful day!';
let doubleQuote = "He said, \"Hello!\"";
console.log(singleQuote); // Outputs: It's a beautiful day!
console.log(doubleQuote); // Outputs: He said, "Hello!"

Using escape sequences allows you to include these characters without causing syntax errors.

Search the web for other special characters and try them out in your strings.

Common String Methods

Strings come with several built-in methods that make it easier to manipulate them. Here are some common methods:

toUpperCase(): Converts the entire string to uppercase.

let greeting = 'Hello, World!';
let upperCaseGreeting = greeting.toUpperCase();
console.log(upperCaseGreeting); // Outputs: HELLO, WORLD!

toLowerCase(): Converts the entire string to lowercase.

let greeting = 'Hello, World!';
let lowerCaseGreeting = greeting.toLowerCase();
console.log(lowerCaseGreeting); // Outputs: hello, world!

includes(): Checks if the string contains a specified substring.

let phrase = 'The quick brown fox jumps over the lazy dog';
console.log(phrase.includes('fox')); // Outputs: true
console.log(phrase.includes('cat')); // Outputs: false

indexOf(): Returns the index of the first occurrence of a specified value in the string. If the value is not found, it returns -1.

let phrase = 'The quick brown fox jumps over the lazy dog';
console.log(phrase.indexOf('fox')); // Outputs: 16
console.log(phrase.indexOf('cat')); // Outputs: -1

slice(): Extracts a part of the string and returns it as a new string, without modifying the original string.

let message = 'Hello, World!';
let greeting = message.slice(0, 5); // Extracts characters from index 0 to 4
console.log(greeting); // Outputs: Hello

substring(): Similar to slice(), but cannot accept negative indices.

let message = 'Hello, World!';
let greeting = message.substring(0, 5);
console.log(greeting); // Outputs: Hello

split(): Splits a string into an array of substrings based on a specified separator. This one can be particularly useful so I have a few more examples to ensure you understand how it works:

// Splitting on Space Character
const sentence = 'This is a sentence';
const words = sentence.split(' '); // Split on every space character
console.log(words); // Outputs: ['This', 'is', 'a', 'sentence']

// Splitting on Comma Character
const csvData = 'apple,banana,cherry,date';
const fruits = csvData.split(','); // Split on every comma
console.log(fruits); // Outputs: ['apple', 'banana', 'cherry', 'date']

// Splitting on a Specific Word
const text = 'helloWORLDhello';
const parts = text.split('WORLD'); // Split on the word 'WORLD'
console.log(parts); // Outputs: ['hello', 'hello']

// Splitting on Each Character
const word = 'JavaScript';
const characters = word.split(''); // Split on each character by using empty string
console.log(characters); // Outputs: ['J', 'a', 'v', 'a', 'S', 'c', 'r', 'i', 'p', 't']

trim(): Removes whitespace from both ends of a string.

let paddedMessage = '   Hello, World!   ';
let trimmedMessage = paddedMessage.trim();
console.log(trimmedMessage); // Outputs: Hello, World!

Skills to Practice

  1. Creating Strings: Use single quotes, double quotes, or backticks to create strings.

    • Examples: 'Hello', "JavaScript", `Template literal`
  2. Getting the Length: Use the length property to determine how many characters are in a string.

    • Example: message.length
  3. Accessing Characters: Use bracket notation with an index to access individual characters.

    • Example: message[0]
  4. Template Literals: Use backticks to create template literals for embedded expressions and multi-line strings.

    • Examples: `Hello, ${name}!`, `Line 1\nLine 2`
  5. Common Methods: Use methods like toUpperCase(), toLowerCase(), includes(), indexOf(), slice(), substring(), split(), and trim() to manipulate strings.

    • Examples: greeting.toUpperCase(), phrase.includes('fox')
  6. Combining Strings: Use the + operator or concat() method to combine strings.

    • Examples: firstName + ' ' + lastName, firstName.concat(' ', lastName)

Strings are a very common tool in JavaScript, so don't rush. Take your time to understand and learn them and it'll pay off for a long time in your career.

Next, we will explore objects which allow us to store data in key-value pairs.

BeginnerJavaScript
Avatar for Niall Maher

Written by Niall Maher

Founder of Codú - The web developer community! I've worked in nearly every corner of technology businesses: Lead Developer, Software Architect, Product Manager, CTO, and now happily a Founder.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.