← Back to Chapters

JavaScript Strings

? JavaScript Strings

⚡ Quick Overview

A string in JavaScript is a sequence of characters used to represent textual data, such as words, sentences, or even single characters.

Strings are one of the primitive data types in JavaScript, meaning they hold simple, immutable data. When you create or manipulate a string, you are working with a value that cannot be changed directly.

JavaScript allows you to create strings using single quotes, double quotes, or backticks (template literals).

? Key Concepts

  • Primitive type: Strings are primitive and immutable.
  • Literals: You can use '...', "...", or `...` to define strings.
  • Immutability: String methods return new strings; the original is not modified.
  • Methods: Rich set of built-in methods for transforming and querying strings.
  • Searching: Methods like indexOf(), includes(), and search() help find text.
  • Template literals: Backtick strings with embedded expressions using ${...} and easy multi-line support.

? Syntax and Theory

Creating strings with different delimiters:

? Basic String Declaration
let single = 'Hello';
let double = "World";
let template = `Hello World!`;

JavaScript treats these forms mostly the same for basic strings, but template literals (backticks) provide extra features:

  • Expression interpolation with ${expression}
  • Multi-line strings without using \n

Because strings are immutable, operations such as toUpperCase(), slice(), or replace() always return a new string instead of changing the original.

? Use Cases

  • Displaying messages and labels in the UI.
  • Storing user input such as names, emails, and comments.
  • Building dynamic messages (e.g., greetings, status texts).
  • Parsing CSV or structured text using split().
  • Searching text for keywords or patterns (often with regular expressions).

? Code Examples

? Creating Basic Strings
let single = 'Hello';
let double = "World";
let template = `Hello World!`;

console.log(single);
console.log(double);
console.log(template);
?️ Common String Methods
const str = " Hello, JavaScript! ";

console.log(str.length);
// 19 - Counts every character including spaces

console.log(str.toUpperCase());
// " HELLO, JAVASCRIPT! " - Converts all letters to uppercase

console.log(str.toLowerCase());
// " hello, javascript! " - Converts all letters to lowercase

console.log(str.charAt(7));
// "J" - Gets the character at index 7

console.log(str.substring(7, 17));
// "JavaScript" - Extracts characters from index 7 to 16

console.log(str.slice(-10, -1));
// "JavaScrip" - Extracts last 10 to last 2 characters

console.log(str.split(", "));
// [" Hello", "JavaScript! "] - Splits string into array by comma and space

console.log(str.trim());
// "Hello, JavaScript!" - Removes whitespace from both ends

console.log(str.replace("JavaScript", "World"));
// " Hello, World! " - Replaces "JavaScript" with "World"

console.log(str.includes("Script"));
// true - Checks if "Script" is in the string
? Searching Inside Strings
const text = "Hello, welcome to the JavaScript world.";

console.log(text.indexOf("welcome"));
// 7 - "welcome" starts at index 7

console.log(text.lastIndexOf("o"));
// 29 - Last "o" appears at index 29

console.log(text.startsWith("Hello"));
// true - String starts with "Hello"

console.log(text.endsWith("world."));
// true - String ends with "world."

console.log(text.search(/JavaScript/i));
// 21 - Case-insensitive search for "JavaScript"
? Using Template Literals
const name = "Alice";
const age = 25;

// Using template literals to embed variables in string
const greeting = `Hello, my name is ${name} and I am ${age} years old.`;
console.log(greeting);
// "Hello, my name is Alice and I am 25 years old."

// Multi-line strings are easy with template literals
const multiline = `This is line 1.
This is line 2.
This is line 3.`;
console.log(multiline);

? Output and Explanation

? What the Previous Code Does

  • Length & case methods: length counts all characters; toUpperCase() and toLowerCase() create new strings in different cases.
  • Character access: charAt(7) returns the character at index 7 (zero-based indexing).
  • Substrings: substring(7, 17) returns characters from index 7 up to (but not including) 17.
  • Negative indexes: slice(-10, -1) counts from the end of the string.
  • Splitting: split(", ") returns an array by cutting the string at each ", ".
  • Trimming: trim() removes spaces at the start and end of the string.
  • Replacing: replace("JavaScript", "World") swaps only the first occurrence.
  • Searching: includes("Script") returns true if the substring exists.
  • Pattern search: search(/JavaScript/i) uses a regular expression to find text, ignoring case.
  • Template literals: Using ${name} and ${age} inserts values directly into the string and keeps multi-line text readable.

? Interactive Example

Enter any text and see how string methods transform it:

? Results

Uppercase: -

Trimmed: -

Length: -

Includes "JS"? -

? Tips and Best Practices

  • Use trim() to clean user input by removing unwanted spaces.
  • Template literals simplify string construction, especially when combining variables and text.
  • Use includes() instead of indexOf() for easier substring existence checks.
  • Remember that string methods return new strings; original strings stay unchanged because strings are immutable.

? Try It Yourself

  • Create a string and convert it to uppercase and lowercase using the respective methods.
  • Extract a substring from a sentence using substring() and slice() and observe differences.
  • Check if a string contains a particular word using includes() and indexOf().
  • Build a sentence using template literals, embedding multiple variables.
  • Split a comma-separated string into an array using split().