Chapter 16 of 31

JavaScript Strings

In JavaScript, we often need to work with text—usernames, messages, email addresses, product names, sentences, and much more.

For example:

let name = "John";

The value "John" is a string.

Strings are one of the most commonly used data types in JavaScript, so let's understand how they work.

What is a String?

A string is a sequence of characters used to represent text.

For example:

let name = "John";
let city = "Delhi";
let message = "Welcome to JavaScript!";

All three values are strings.


Creating Strings

JavaScript provides three common ways to create strings.

Double Quotes

let name = "John";

Single Quotes

let name = 'John';

Backticks

let name = `John`;

All three create strings.

Backticks are called template literals, and they provide some extra features that we'll see shortly.


String Length

The .length property tells us how many characters a string contains.

let message = "Hello";

console.log(message.length);

Output:

5

Spaces are also counted as characters.

let message = "Hello World";

console.log(message.length);

Output:

11

Accessing Characters

Just like arrays, strings use zero-based indexing.

let word = "Hello";

console.log(word[0]);
console.log(word[1]);
console.log(word[4]);

Output:

H
e
o

The indexes look like this:

Index

Character

0

H

1

e

2

l

3

l

4

o

We can also use at():

console.log(word.at(-1));

Output:

o

This is useful when accessing characters from the end of a string.


Strings Are Immutable

Strings in JavaScript are immutable, which means we cannot directly change an individual character.

For example:

let word = "Hello";

word[0] = "Y";

console.log(word);

The string remains:

Hello

Instead, we create a new string:

let word = "Hello";

word = "Y" + word.slice(1);

console.log(word);

Output:

Yello

This is different from arrays, which can have individual elements changed.


Combining Strings

We can combine strings using the + operator.

let firstName = "John";
let lastName = "Smith";

let fullName = firstName + " " + lastName;

console.log(fullName);

Output:

John Smith

This is called string concatenation.


Template Literals

For combining text with variables, template literals are often much cleaner.

They use backticks:

let name = "John";
let age = 21;

console.log(`My name is ${name} and I am ${age} years old.`);

Output:

My name is John and I am 21 years old.

The ${} syntax allows us to insert variables or expressions directly inside the string.

For example:

let price = 100;
let quantity = 3;

console.log(`Total price: ${price * quantity}`);

Output:

Total price: 300

Template literals can also span multiple lines:

let message = `Hello John,
Welcome to our website!`;

console.log(message);

Common String Methods

JavaScript provides many built-in methods for working with strings.

Some important ones are:

Method

Purpose

toUpperCase()

Converts to uppercase

toLowerCase()

Converts to lowercase

trim()

Removes spaces from both ends

includes()

Checks whether text exists

startsWith()

Checks the beginning

endsWith()

Checks the ending

indexOf()

Finds the position of text

slice()

Extracts part of a string

substring()

Extracts part of a string

replace()

Replaces text

split()

Converts a string into an array

Let's look at some of the most useful ones.


toUpperCase() and toLowerCase()

These methods change the letter case.

let message = "Hello World";

console.log(message.toUpperCase());
console.log(message.toLowerCase());

Output:

HELLO WORLD
hello world

This is useful when comparing text where letter case shouldn't matter.


trim()

trim() removes whitespace from the beginning and end of a string.

let name = "   John   ";

console.log(name.trim());

Output:

John

This is especially useful when processing user input from forms.


includes()

includes() checks whether a string contains a specific piece of text.

let message = "Welcome to JavaScript";

console.log(message.includes("JavaScript"));

Output:

true

If the text doesn't exist:

console.log(message.includes("Python"));

Output:

false

startsWith() and endsWith()

These methods check whether a string starts or ends with specific text.

let fileName = "photo.jpg";

console.log(fileName.startsWith("photo"));
console.log(fileName.endsWith(".jpg"));

Output:

true
true

These can be useful when checking filenames, URLs, or other text patterns.


indexOf()

indexOf() returns the position of the first occurrence of some text.

let message = "Hello World";

console.log(message.indexOf("World"));

Output:

6

Remember that indexing starts from 0.

If the text isn't found, it returns -1.

console.log(message.indexOf("JavaScript"));

Output:

-1

slice()

slice() extracts part of a string and returns a new string.

let message = "Hello World";

console.log(message.slice(0, 5));

Output:

Hello

The ending index is not included.

We can also use negative indexes:

console.log(message.slice(-5));

Output:

World

replace()

The replace() method replaces part of a string.

let message = "Hello John";

let result = message.replace("John", "Alex");

console.log(result);

Output:

Hello Alex

The original string isn't changed because strings are immutable.


split()

split() breaks a string into an array.

For example:

let fruits = "Apple,Banana,Mango";

let result = fruits.split(",");

console.log(result);

Output:

["Apple", "Banana", "Mango"]

This is very useful when converting text into a list of values.

For example:

let sentence = "Hello World";

console.log(sentence.split(" "));

Output:

["Hello", "World"]

Comparing Strings

We can compare strings using comparison operators.

let a = "apple";
let b = "apple";

console.log(a === b);

Output:

true

String comparison is case-sensitive:

console.log("hello" === "Hello");

Output:

false

If you want a case-insensitive comparison, you can normalize both strings:

let input = "HELLO";

console.log(input.toLowerCase() === "hello");

Output:

true

A Practical Example

Let's say we're processing a username entered by a user.

let username = "   JOHN   ";

username = username.trim().toLowerCase();

console.log(username);

Output:

john

Here, we:

  1. Used trim() to remove unnecessary spaces.

  2. Used toLowerCase() to convert the text to lowercase.

This kind of string processing is very common when handling user input.

Conclusion

Strings are used whenever our JavaScript program needs to work with text.

Some important things to remember:

  • Strings can be created using ' ', " ", or backticks.

  • String indexes start from 0.

  • Strings are immutable.

  • .length gives the number of characters.

  • + can combine strings.

  • Template literals make it easy to insert variables into text.

  • Methods such as trim(), includes(), slice(), replace(), and split() make string processing much easier.

Once you become comfortable with strings and their methods, you'll be able to handle everything from usernames and messages to form input and API data much more easily.