""
Index

Strings and String Methods

JavaScript for Beginners

14.1 Common String Methods (slice, substr, replace, split, trim)

JavaScript strings come with many built-in methods that help you manipulate text easily. In this section, we'll explore some of the most commonly used string methods:

Each method serves a specific purpose, such as extracting parts of a string, replacing content, splitting strings into arrays, or removing unwanted whitespace.

slice()

The slice() method extracts a part of a string and returns it as a new string without modifying the original.

Syntax:

string.slice(startIndex, endIndex)

Example:

const fullName = "Jane Doe";

// Extract first name (characters from index 0 to 4)
const firstName = fullName.slice(0, 4);
console.log(firstName);  // Output: "Jane"

// Extract last name (from index 5 to end)
const lastName = fullName.slice(5);
console.log(lastName);   // Output: "Doe"

substr()

The substr() method extracts a substring starting from a given index and for a specified length.

Syntax:

string.substr(startIndex, length)

Example:

const url = "https://example.com/page";

// Extract "example"
const domain = url.substr(8, 7);
console.log(domain);  // Output: "example"

Note: substr() is considered a legacy method and may not be supported in all environments. slice() or substring() are generally preferred.

replace()

The replace() method replaces part of a string with another string. It returns a new string without changing the original.

Syntax:

string.replace(searchValue, newValue)

Example:

const greeting = "Hello, world!";
const newGreeting = greeting.replace("world", "JavaScript");
console.log(newGreeting);  // Output: "Hello, JavaScript!"

By default, replace() only changes the first match. To replace all occurrences, use a regular expression with the global flag /g:

const sentence = "Apples are red. Apples are sweet.";
const updated = sentence.replace(/Apples/g, "Oranges");
console.log(updated);
// Output: "Oranges are red. Oranges are sweet."

split()

The split() method divides a string into an array of substrings based on a specified separator.

Syntax:

string.split(separator, limit)

Example:

const sentence = "JavaScript,Python,Ruby,Java";

// Split by commas
const languages = sentence.split(",");
console.log(languages);  // Output: ["JavaScript", "Python", "Ruby", "Java"]

// Split into maximum 2 parts
const limitedSplit = sentence.split(",", 2);
console.log(limitedSplit);  // Output: ["JavaScript", "Python"]

trim()

The trim() method removes whitespace from both ends of a string but not from inside the string.

Syntax:

string.trim()

Example:

const rawInput = "   user@example.com   ";
const cleanedInput = rawInput.trim();
console.log(cleanedInput);  // Output: "user@example.com"

This is especially useful when processing user input to avoid errors caused by accidental spaces.

Summary

Method Purpose Key Parameters Example Use Case
slice Extract substring by start/end startIndex, endIndex Get first or last name
substr Extract substring by start/length startIndex, length Extract part of URL
replace Replace substring searchValue, newValue Replace words in sentences
split Split string into array separator, limit Parse CSV or list strings
trim Remove whitespace around string None Clean user input

By mastering these common string methods, you'll be able to manipulate and transform text efficiently in your JavaScript programs!

Index

14.2 Template Literals

Template literals are a modern and powerful way to work with strings in JavaScript. Introduced in ES6, they offer a more readable and flexible alternative to traditional string concatenation.

What Are Template Literals?

Template literals are strings enclosed by backticks () instead of single (') or double ("`) quotes.

const message = `Hello, world!`;

Using backticks lets you easily:

Benefits Over Traditional Concatenation

Instead of this:

const name = "Alice";
const age = 25;

const greeting = "Hello, " + name + "! You are " + age + " years old.";
console.log(greeting);

With template literals, you can write:

const name = "Alice";
const age = 25;

const greeting = `Hello, ${name}! You are ${age} years old.`;
console.log(greeting);

The second version is clearer, shorter, and easier to maintain.

Variable Interpolation with {}

Inside a template literal, anything placed inside ${} is evaluated as JavaScript code and its result is inserted into the string.

const price = 9.99;
const quantity = 3;

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

You can embed variables, mathematical expressions, function calls, or any valid JavaScript expression.

Multi-line Strings

With traditional strings, to create a multi-line string, you had to use escape characters \n or concatenate strings:

const poem = "Roses are red,\nViolets are blue,\nJavaScript is fun,\nAnd so are you.";

With template literals, you can simply write:

const poem = `Roses are red,
Violets are blue,
JavaScript is fun,
And so are you.`;

console.log(poem);

This preserves line breaks and formatting exactly as written.

Mini-Project: Dynamic Greeting and HTML Snippet Generator

Let's create a small example that generates a personalized greeting and an HTML snippet using template literals.

function createGreeting(name, dayOfWeek) {
  return `
    <div class="greeting">
      <h1>Hello, ${name}!</h1>
      <p>Hope you're having a great ${dayOfWeek}.</p>
      <p>Today is ${new Date().toLocaleDateString()}.</p>
    </div>
  `;
}

const userName = "Sam";
const today = "Tuesday";

const greetingHTML = createGreeting(userName, today);
console.log(greetingHTML);

Output:

<div class="greeting">
  <h1>Hello, Sam!</h1>
  <p>Hope you're having a great Tuesday.</p>
  <p>Today is 6/23/2025.</p>
</div>

This HTML string can be injected into a webpage dynamically, demonstrating how template literals make string building easier and cleaner.

Summary

Try replacing your old concatenation code with template literals — your future self will thank you!

Index

14.3 String Searching and Pattern Matching

Finding and matching specific parts of a string is a common task in JavaScript. This section introduces simple methods for searching strings as well as an introduction to regular expressions (RegExp) for more powerful pattern matching.

Simple String Searching Methods

JavaScript provides several built-in methods to search within strings:

Method Description Returns
indexOf() Finds the index of a substring Index number or -1 if not found
includes() Checks if a substring exists true or false
startsWith() Checks if string begins with a substring true or false
endsWith() Checks if string ends with a substring true or false

indexOf()

Returns the position of the first occurrence of a substring. If not found, returns -1.

const text = "JavaScript is fun";

console.log(text.indexOf("Script"));  // Output: 4
console.log(text.indexOf("python"));  // Output: -1 (not found)

includes()

Returns true if the substring exists anywhere in the string, otherwise false.

const email = "user@example.com";

console.log(email.includes("@"));       // Output: true
console.log(email.includes("gmail"));   // Output: false

startsWith() and endsWith()

Check if a string starts or ends with a specified substring.

const url = "https://example.com";

console.log(url.startsWith("https"));  // true
console.log(url.endsWith(".com"));     // true
console.log(url.startsWith("http"));   // true
console.log(url.endsWith(".org"));      // false

Introduction to Regular Expressions (RegExp)

When simple substring searches are not enough, regular expressions provide a flexible way to match complex patterns in strings.

A RegExp is a pattern used to match character combinations.

You create regex patterns with:

const pattern = /pattern/flags;

or

const pattern = new RegExp("pattern", "flags");

Using RegExp for Searches

Example: Check if a string contains only digits

const input = "12345";
const digitPattern = /^\d+$/;  // ^ = start, \d = digit, + = one or more, $ = end

console.log(digitPattern.test(input));  // true
console.log(digitPattern.test("123a5")); // false

Practical Use Case: Validate an Email Format

Here is a simple regex to validate a basic email format:

const email = "user@example.com";
const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

if (emailPattern.test(email)) {
  console.log("Valid email address.");
} else {
  console.log("Invalid email address.");
}

Searching With RegExp Methods

You can also use .match() to find matches:

const sentence = "I have 2 cats and 3 dogs.";
const numbers = sentence.match(/\d+/g);  // Find all numbers

console.log(numbers);  // Output: ["2", "3"]

Summary

Method Purpose Returns
indexOf() Position of substring Number or -1
includes() Check if substring exists Boolean
startsWith() Check prefix of string Boolean
endsWith() Check suffix of string Boolean
RegExp.test() Test if string matches pattern Boolean
String.match() Find matches for regex Array of matches or null

Final Note

For simple substring searches, indexOf, includes, startsWith, and endsWith are straightforward and efficient. For more advanced pattern matching and validation — such as email formats, phone numbers, or custom rules — regular expressions are an invaluable tool.

With practice, you’ll gain the ability to harness both simple methods and regex to build robust string handling in your JavaScript programs!

Index