String in JavaScript

🧠 What is a String?

A string in JavaScript is a sequence of characters used to represent text. Strings can include letters, numbers, symbols, and even emoji! They are one of the most commonly used data types in JavaScript.

>>“Strings are the soul of textual data in JavaScript.” 💬

📌 Declaring Strings

You can create strings using:

  • "" – double quotes
  • '' – single quotes
  • `` – backticks for template literals

String Declaration

let name1 = "Alice";
let name2 = 'Bob';
let message = `Hello, ${name1}!`;

Note

💡 Use backticks (`) when you need to embed variables or write multiline strings.

✂️ Common String Methods

JavaScript provides many built-in methods to work with strings:

MethodDescription
lengthReturns the number of characters
toUpperCase()Converts to uppercase
toLowerCase()Converts to lowercase
includes()Checks if substring exists
indexOf()Returns position of substring
trim()Removes whitespace
slice(start, end)Extracts part of string
replace()Replaces substring

String Method Examples

let str = "  JavaScript is fun!  ";
console.log(str.length);            // 22
console.log(str.trim());            // "JavaScript is fun!"
console.log(str.toUpperCase());     // "  JAVASCRIPT IS FUN!  "
console.log(str.includes("fun"));   // true
console.log(str.indexOf("Script")); // 4
console.log(str.slice(2, 13));      // "JavaScript"
console.log(str.replace("fun", "awesome")); // "  JavaScript is awesome!  "

🧩 Template Literals

Template literals (strings inside backticks) let you embed expressions using ${expression}.

Template Literals

let name = "Alice";
let age = 25;

let message = `My name is ${name} and I am ${age} years old.`;
console.log(message);
// Output: "My name is Alice and I am 25 years old."

Note

📌 Template literals also support multiline strings without \\n.

📚 Escape Characters

Strings can contain special characters using escape sequences:

Escape Characters

let quote = "She said, \"Hello!\"";
let path = "C:\\Users\\Admin";
let multiline = "Line1\nLine2\nLine3";

📐 String Immutability

Strings in JavaScript are immutable, meaning their content cannot be changed after creation. Any operation on a string returns a new string.

String Immutability

let msg = "hello";
msg[0] = "H";       // ❌ No effect
console.log(msg);   // "hello"

Note

✏️ Use methods like replace() or string concatenation to modify strings.

🔚 Summary

  • 📦 Strings store and manipulate text
  • 🧱 Created using single, double, or backtick quotes
  • 🔧 String methods help you work with text efficiently
  • 📏 Strings are immutable — they can't be changed directly

📖 Resources

>>“Code is read more often than it is written — keep your strings clean and expressive.” ✍️