Chapter 17 of 31

JavaScript String Methods

In the previous topic, we learned what strings are and how JavaScript represents text.

But when working with real applications, simply storing a string isn't enough. We often need to search text, change its case, remove spaces, extract parts, replace words, or split text into pieces.

JavaScript provides built-in string methods to make all of this easier.

What are String Methods?

String methods are built-in functions that allow us to perform different operations on strings.

For example:

let message = "Hello World";

console.log(message.toUpperCase());

Output:

HELLO WORLD

Here, toUpperCase() is a string method.

Remember that strings are immutable. Most string methods return a new string instead of changing the original string.


Common String Methods

Here are some of the most useful methods:

Method

Purpose

toUpperCase()

Converts text to uppercase

toLowerCase()

Converts text to lowercase

trim()

Removes whitespace from both ends

trimStart()

Removes whitespace from the beginning

trimEnd()

Removes whitespace from the end

includes()

Checks whether text exists

startsWith()

Checks the beginning

endsWith()

Checks the ending

indexOf()

Finds the position of text

lastIndexOf()

Finds the last position of text

charAt()

Gets a character at an index

slice()

Extracts part of a string

substring()

Extracts part of a string

replace()

Replaces text

replaceAll()

Replaces all matching text

split()

Converts a string into an array

concat()

Joins strings

repeat()

Repeats a string

Let's look at the important ones.


1. toUpperCase()

Converts all letters in a string to uppercase.

let message = "Hello World";

console.log(message.toUpperCase());

Output:

HELLO WORLD

The original string is not changed.

console.log(message);

Output:

Hello World

2. toLowerCase()

Converts all letters to lowercase.

let message = "Hello World";

console.log(message.toLowerCase());

Output:

hello world

This is particularly useful when comparing user input.

let input = "YES";

if (input.toLowerCase() === "yes") {
    console.log("User said yes.");
}

3. trim()

trim() removes whitespace from both ends of a string.

let name = "   John   ";

console.log(name.trim());

Output:

John

This is very useful when processing form input.


4. trimStart() and trimEnd()

Sometimes we only want to remove whitespace from one side.

let text = "   Hello   ";

console.log(text.trimStart());
console.log(text.trimEnd());

Output:

Hello   
   Hello

So:

trim()       → Both sides
trimStart()  → Beginning
trimEnd()    → End

5. includes()

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

It returns true or false.

let message = "Welcome to JavaScript";

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

Output:

true

If it doesn't exist:

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

Output:

false

6. startsWith()

Checks whether a string starts with specific text.

let fileName = "photo.jpg";

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

Output:

true

7. endsWith()

Checks whether a string ends with specific text.

let fileName = "photo.jpg";

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

Output:

true

These methods are useful when validating filenames, URLs, usernames, and other text.


8. indexOf()

indexOf() returns the index of the first occurrence of a specified string.

let message = "Hello World";

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

Output:

6

Remember, indexing starts at 0.

If the text isn't found:

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

Output:

-1

9. lastIndexOf()

lastIndexOf() finds the position of the last occurrence of some text.

let message = "JavaScript is great. I love JavaScript.";

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

It returns the index where the final "JavaScript" begins.

This is useful when a string contains the same text multiple times.


10. charAt()

charAt() returns the character at a specific index.

let word = "Hello";

console.log(word.charAt(0));
console.log(word.charAt(4));

Output:

H
o

You can also use bracket notation:

console.log(word[0]);

Both approaches are commonly seen.


11. slice()

slice() extracts a portion of a string.

let message = "Hello World";

let result = message.slice(0, 5);

console.log(result);

Output:

Hello

The ending index is not included.

slice(0, 5)
      ↑  ↑
    start end

So indexes 0 through 4 are extracted.

You can also use negative indexes:

let message = "Hello World";

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

Output:

World

12. substring()

substring() also extracts part of a string.

let message = "Hello World";

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

Output:

Hello

For most everyday use, slice() is often more convenient because it supports negative indexes.


13. replace()

replace() replaces a matching piece of text.

let message = "Hello John";

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

console.log(result);

Output:

Hello Alex

The original string remains unchanged.

By default, replace() replaces only the first matching occurrence when given a string.

For example:

let text = "apple apple apple";

console.log(text.replace("apple", "orange"));

Output:

orange apple apple

14. replaceAll()

If we want to replace all occurrences, we can use replaceAll().

let text = "apple apple apple";

console.log(text.replaceAll("apple", "orange"));

Output:

orange orange orange

So:

replace()    → First matching occurrence
replaceAll() → All matching occurrences

15. split()

split() breaks a string into an array based on a separator.

For example:

let fruits = "Apple,Banana,Mango";

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

console.log(result);

Output:

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

We can also split a sentence by spaces:

let sentence = "Hello World JavaScript";

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

Output:

["Hello", "World", "JavaScript"]

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


16. concat()

concat() combines strings.

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

let fullName = firstName.concat(" ", lastName);

console.log(fullName);

Output:

John Smith

However, in modern JavaScript, the + operator or template literals are often easier to read:

let fullName = `${firstName} ${lastName}`;

17. repeat()

repeat() repeats a string a specified number of times.

let text = "Hello ";

console.log(text.repeat(3));

Output:

Hello Hello Hello

This can be useful when generating repeated text or formatting output.


Chaining String Methods

One really useful feature is that we can chain multiple string methods together.

For example:

let username = "   JOHN   ";

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

console.log(result);

Output:

john

Here JavaScript performs:

"   JOHN   "
      ↓
trim()
      ↓
"JOHN"
      ↓
toLowerCase()
      ↓
"john"

This kind of method chaining is very common in JavaScript.


Practical Example

Let's say a user enters an email address into a form:

let email = "   JOHN@EXAMPLE.COM   ";

email = email.trim().toLowerCase();

if (email.endsWith("@example.com")) {
    console.log("Valid company email.");
}

The input becomes:

john@example.com

Then endsWith() checks whether it belongs to the expected domain.

This small example combines three useful string methods:

trim()         → Removes unnecessary spaces
toLowerCase()  → Normalizes the text
endsWith()     → Checks the ending

Important String Methods at a Glance

Method

Example

Result

toUpperCase()

"hello".toUpperCase()

"HELLO"

toLowerCase()

"HELLO".toLowerCase()

"hello"

trim()

" hi ".trim()

"hi"

includes()

"Hello".includes("ell")

true

startsWith()

"Hello".startsWith("He")

true

endsWith()

"Hello".endsWith("lo")

true

indexOf()

"Hello".indexOf("l")

2

charAt()

"Hello".charAt(1)

"e"

slice()

"Hello".slice(1, 4)

"ell"

replace()

"Hi John".replace("John", "Alex")

"Hi Alex"

split()

"A,B,C".split(",")

["A","B","C"]

repeat()

"Hi ".repeat(2)

"Hi Hi "

Conclusion

String methods make it much easier to work with text in JavaScript. Instead of manually writing complicated logic, we can use built-in methods for common operations.

The most important ones to remember are:

toUpperCase()
toLowerCase()
trim()
includes()
startsWith()
endsWith()
indexOf()
slice()
replace()
replaceAll()
split()

A good beginner habit is to learn what each method does rather than trying to memorize every method at once. As you build real applications, you'll naturally start using them again and again.