Progress6 of 20 topics

30% complete

JavaScript Strings

Strings are one of the most common data types in JavaScript, used to represent text. Whether you're displaying messages, processing user input, or manipulating text, understanding how to work with strings is essential for any JavaScript developer.

Real-World Analogy

Think of a string like a necklace with beads:

  • Each character is like a bead on the necklace
  • The characters are arranged in a specific order
  • You can count the beads (length), add more (concatenation), or remove some (substring)
  • You can find specific patterns of beads (search methods)

Creating Strings

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

JavaScript
1// Using single quotes
2let firstName = 'John';
3
4// Using double quotes
5let lastName = "Doe";
6
7// Using backticks (template literals - ES6)
8let greeting = `Hello, ${firstName} ${lastName}!`;
9
10console.log(greeting); // Outputs: Hello, John Doe!
11
12// Strings with quotes inside
13let singleInDouble = "It's a beautiful day"; // Single quote inside double quotes
14let doubleInSingle = 'He said, "Hello!"'; // Double quotes inside single quotes
15let escapeQuotes = 'It\'s a beautiful day'; // Escaping with backslash
16
17// Empty string
18let emptyString = "";
19
20// String with numbers (still a string)
21let age = "30"; // This is a string, not a number

String Properties

The most important property of a string is its length.

JavaScript
1// String length
2let message = "Hello, World!";
3console.log(message.length); // Outputs: 13 (counts all characters including spaces and punctuation)
4
5// Checking if a string is empty
6let emptyString = "";
7let isEmptyUsingLength = emptyString.length === 0; // true
8let isEmptyDirectCheck = emptyString === ""; // true

Accessing Characters

You can access individual characters in a string using bracket notation with the index position. Remember that string indices start at 0, not 1.

JavaScript
1// Accessing characters by index
2let greeting = "Hello";
3
4console.log(greeting[0]); // Outputs: "H"
5console.log(greeting[1]); // Outputs: "e"
6console.log(greeting[4]); // Outputs: "o"
7
8// Trying to access an index that doesn't exist
9console.log(greeting[5]); // Outputs: undefined
10
11// Strings are immutable (cannot be changed)
12greeting[0] = "J"; // This does nothing
13console.log(greeting); // Still outputs: "Hello"
14
15// Getting the last character
16let lastChar = greeting[greeting.length - 1]; // "o"
17
18// Using charAt() method (alternative to bracket notation)
19console.log(greeting.charAt(0)); // Outputs: "H"
20console.log(greeting.charAt(10)); // Outputs: "" (empty string, not undefined)

Important: Strings are Immutable

In JavaScript, strings are immutable, which means you cannot change individual characters of a string after it's created. Instead, you create a new string with the changes you want.

JavaScript
// This doesn't work
let name = "John";
name[0] = "T"; // No effect
console.log(name); // Still "John"
// This works
name = "T" + name.substring(1); // Create a new string
console.log(name); // "Tohn"

String Methods

JavaScript provides many built-in methods for working with strings. Let's explore the most commonly used ones.

Case Conversion

JavaScript
1// Converting case
2let message = "Hello, World!";
3
4console.log(message.toUpperCase()); // "HELLO, WORLD!"
5console.log(message.toLowerCase()); // "hello, world!"
6
7// Original string remains unchanged
8console.log(message); // "Hello, World!"
9
10// Practical example: Case-insensitive comparison
11let userInput = "JavaScript";
12let storedValue = "javascript";
13
14if (userInput.toLowerCase() === storedValue.toLowerCase()) {
15 console.log("The values match (ignoring case)!");
16}

Finding Substrings

JavaScript
1// Checking if a string contains a substring
2let sentence = "JavaScript is fun to learn";
3
4// indexOf returns the position of the first occurrence (-1 if not found)
5console.log(sentence.indexOf("Script")); // 4
6console.log(sentence.indexOf("Java")); // 0
7console.log(sentence.indexOf("Python")); // -1 (not found)
8
9// lastIndexOf returns the position of the last occurrence
10let repeatedText = "hello hello hello";
11console.log(repeatedText.lastIndexOf("hello")); // 12
12
13// includes returns true if the string contains the substring (ES6)
14console.log(sentence.includes("fun")); // true
15console.log(sentence.includes("boring")); // false
16
17// startsWith and endsWith (ES6)
18console.log(sentence.startsWith("Java")); // true
19console.log(sentence.endsWith("learn")); // true
20
21// Checking with specific position
22console.log(sentence.startsWith("Script", 4)); // true (start checking from index 4)

Extracting Substrings

JavaScript
1// Extracting parts of a string
2let message = "Hello, World!";
3
4// slice(start, end) - extracts from start to end (end not included)
5console.log(message.slice(0, 5)); // "Hello"
6console.log(message.slice(7, 12)); // "World"
7console.log(message.slice(7)); // "World!" (to the end)
8console.log(message.slice(-6)); // "World!" (from the end)
9console.log(message.slice(-6, -1)); // "World" (from the end)
10
11// substring(start, end) - similar to slice but doesn't support negative indices
12console.log(message.substring(0, 5)); // "Hello"
13console.log(message.substring(7, 12)); // "World"
14
15// substr(start, length) - extracts length characters from start
16// Note: substr() is deprecated, but still works
17console.log(message.substr(0, 5)); // "Hello"
18console.log(message.substr(7, 5)); // "World"
19console.log(message.substr(-6, 5)); // "World" (from the end)

slice vs. substring

slice: Supports negative indices (counting from the end)

JavaScript
let str = "JavaScript";
console.log(str.slice(-6)); // "Script"
console.log(str.slice(4, 10)); // "Script"

slice vs. substring

substring: Treats negative indices as 0, swaps arguments if start > end

JavaScript
let str = "JavaScript";
console.log(str.substring(-6)); // "JavaScript" (treats -6 as 0)
console.log(str.substring(10, 4)); // "Script" (swaps 10 and 4)

Replacing Content

JavaScript
1// Replacing content in strings
2let message = "Hello, World!";
3
4// replace() - replaces the first occurrence
5let newMessage = message.replace("Hello", "Hi");
6console.log(newMessage); // "Hi, World!"
7
8// replace() only replaces the first occurrence by default
9let text = "apple apple apple";
10console.log(text.replace("apple", "orange")); // "orange apple apple"
11
12// To replace all occurrences (ES2021 and later)
13console.log(text.replaceAll("apple", "orange")); // "orange orange orange"
14
15// For older browsers, use regular expression with global flag
16console.log(text.replace(/apple/g, "orange")); // "orange orange orange"
17
18// replace() is case-sensitive
19let caseSensitive = "Hello hello";
20console.log(caseSensitive.replace("hello", "hi")); // "Hello hi"
21
22// Use regular expression with 'i' flag for case-insensitive replace
23console.log(caseSensitive.replace(/hello/i, "hi")); // "hi hello"
24console.log(caseSensitive.replace(/hello/gi, "hi")); // "hi hi" (global + case-insensitive)

Trimming Whitespace

JavaScript
1// Trimming whitespace
2let text = " Hello, World! ";
3
4// trim() removes whitespace from both ends
5console.log(text.trim()); // "Hello, World!"
6
7// trimStart() / trimLeft() removes whitespace from the start
8console.log(text.trimStart()); // "Hello, World! "
9
10// trimEnd() / trimRight() removes whitespace from the end
11console.log(text.trimEnd()); // " Hello, World!"
12
13// Practical example: Cleaning user input
14function validateUsername(username) {
15 const trimmedUsername = username.trim();
16 return trimmedUsername.length >= 3;
17}
18
19console.log(validateUsername(" john ")); // true
20console.log(validateUsername(" jo ")); // false

Padding and Alignment

JavaScript
1// Padding strings (ES2017)
2let number = "42";
3
4// padStart(targetLength, padString) adds padding at the start
5console.log(number.padStart(5, "0")); // "00042"
6console.log(number.padStart(8, "x")); // "xxxxxx42"
7
8// padEnd(targetLength, padString) adds padding at the end
9console.log(number.padEnd(5, "0")); // "42000"
10console.log(number.padEnd(8, "!")); // "42!!!!!!"
11
12// Practical example: Formatting credit card
13let cardNumber = "1234567890123456";
14let lastFour = cardNumber.slice(-4);
15let maskedCard = lastFour.padStart(16, "*");
16console.log(maskedCard); // "************3456"

Splitting and Joining

JavaScript
1// Splitting strings into arrays
2let sentence = "JavaScript is fun to learn";
3
4// split(separator) creates an array by splitting the string
5let words = sentence.split(" ");
6console.log(words); // ["JavaScript", "is", "fun", "to", "learn"]
7
8// Split by other characters
9let csvData = "John,Doe,30,New York";
10let dataArray = csvData.split(",");
11console.log(dataArray); // ["John", "Doe", "30", "New York"]
12
13// Limit the number of splits
14let limitedSplit = sentence.split(" ", 3);
15console.log(limitedSplit); // ["JavaScript", "is", "fun"]
16
17// Split into characters
18let chars = "Hello".split("");
19console.log(chars); // ["H", "e", "l", "l", "o"]
20
21// Joining arrays into strings
22let wordsArray = ["JavaScript", "is", "awesome"];
23let joinedString = wordsArray.join(" ");
24console.log(joinedString); // "JavaScript is awesome"
25
26// Join with different separators
27console.log(wordsArray.join("-")); // "JavaScript-is-awesome"
28console.log(wordsArray.join("")); // "JavaScriptisawesome"
29console.log(wordsArray.join(", ")); // "JavaScript, is, awesome"

Template Literals (ES6)

Template literals (introduced in ES6) provide an easier way to create strings with embedded expressions and multiline content.

JavaScript
1// Basic template literal with variable interpolation
2let name = "Alice";
3let greeting = `Hello, ${name}!`;
4console.log(greeting); // "Hello, Alice!"
5
6// Expressions in template literals
7let a = 5;
8let b = 10;
9console.log(`The sum of ${a} and ${b} is ${a + b}`); // "The sum of 5 and 10 is 15"
10
11// Multiline strings
12let multiline = `This is a string
13that spans multiple
14lines without special characters.`;
15
16console.log(multiline);
17// Outputs:
18// This is a string
19// that spans multiple
20// lines without special characters.
21
22// Tagged templates (advanced)
23function highlight(strings, ...values) {
24 let result = "";
25 strings.forEach((string, i) => {
26 result += string;
27 if (i < values.length) {
28 result += `<strong>${values[i]}</strong>`;
29 }
30 });
31 return result;
32}
33
34let language = "JavaScript";
35let years = 25;
36
37let message = highlight`${language} is over ${years} years old!`;
38console.log(message); // "JavaScript is over <strong>JavaScript</strong> years old!<strong>25</strong>"

String Comparison

Comparing strings in JavaScript is straightforward for exact matches, but there are some nuances to be aware of.

JavaScript
1// Basic comparison
2console.log("apple" === "apple"); // true
3console.log("Apple" === "apple"); // false (case-sensitive)
4
5// Case-insensitive comparison
6console.log("Apple".toLowerCase() === "apple".toLowerCase()); // true
7
8// Comparing alphabetical order
9console.log("apple" < "banana"); // true (a comes before b)
10console.log("apple" > "Apple"); // true (lowercase comes after uppercase in ASCII/Unicode)
11
12// localeCompare for proper alphabetical comparison
13console.log("apple".localeCompare("banana")); // -1 (comes before)
14console.log("banana".localeCompare("apple")); // 1 (comes after)
15console.log("apple".localeCompare("apple")); // 0 (same)
16
17// Locale-aware comparison
18console.log("café".localeCompare("cafe", "en")); // not 0 (different in English)
19console.log("café".localeCompare("cafe", "fr", { sensitivity: 'base' })); // 0 (same in French with base sensitivity)

Escape Sequences

Escape sequences allow you to include special characters in your strings.

Escape SequenceCharacterExample
\'Single quote'It\'s raining'
\"Double quote"She said, \"Hello\""
\\Backslash"C:\\Files\\Document"
\nNew line"Line 1\nLine 2"
\tTab"Name:\tJohn"
\rCarriage return"Text\rOverwrite"
\bBackspace"Hello\b"
JavaScript
1// Escape sequences examples
2console.log("This is a line\nThis is another line");
3// Outputs:
4// This is a line
5// This is another line
6
7console.log("Name:\tJohn\tAge:\t30");
8// Outputs: Name: John Age: 30
9
10console.log("C:\\Program Files\\App");
11// Outputs: C:\Program Files\App

Common String Operations

Let's look at some common string operations you might need to perform.

JavaScript
1// Counting occurrences of a substring
2function countOccurrences(str, subStr) {
3 let count = 0;
4 let position = str.indexOf(subStr);
5
6 while (position !== -1) {
7 count++;
8 position = str.indexOf(subStr, position + 1);
9 }
10
11 return count;
12}
13
14console.log(countOccurrences("banana", "a")); // 3
15
16// Reversing a string
17function reverseString(str) {
18 return str.split("").reverse().join("");
19}
20
21console.log(reverseString("hello")); // "olleh"
22
23// Checking if a string is a palindrome
24function isPalindrome(str) {
25 // Remove non-alphanumeric characters and convert to lowercase
26 const cleanStr = str.replace(/[^a-zA-Z0-9]/g, "").toLowerCase();
27 const reversedStr = cleanStr.split("").reverse().join("");
28 return cleanStr === reversedStr;
29}
30
31console.log(isPalindrome("A man, a plan, a canal: Panama")); // true
32console.log(isPalindrome("hello")); // false
33
34// Capitalizing the first letter of each word
35function capitalizeWords(str) {
36 return str
37 .split(" ")
38 .map(word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
39 .join(" ");
40}
41
42console.log(capitalizeWords("hello world")); // "Hello World"

Practice Exercises

Try these exercises to reinforce your understanding of JavaScript strings:

JavaScript
// 1. Create a function that takes a full name string and returns the initials
// Example: "John Doe" → "J.D."
// 2. Create a function that censors specific words in a string by replacing them with asterisks
// Example: censorWords("This is bad", ["bad"]) → "This is ***"
// 3. Create a function that converts a string to camelCase
// Example: "hello world" → "helloWorld"
// 4. Create a function that truncates a string if it's longer than a specified length
// and adds "..." at the end
// Example: truncate("This is a long text", 10) → "This is a..."
// 5. Create a function that checks if a string contains all the letters of the alphabet
// (a pangram)
// Example: "The quick brown fox jumps over the lazy dog" → true

Summary

In this tutorial, you've learned:

  • How to create strings using different types of quotes
  • How to access and manipulate individual characters
  • How to use various string methods for common operations
  • How to use template literals for more flexible string creation
  • How to compare strings and handle special characters
  • How to perform common string operations like counting, reversing, and capitalizing

Strings are a fundamental part of JavaScript programming, and mastering string manipulation will help you build more effective and user-friendly applications. In the next tutorial, you'll learn about arrays, which are another important data structure in JavaScript.

Related Tutorials

Learn about different types of data and how to store them in JavaScript.

Learn more

Learn how to create and use functions in JavaScript.

Learn more

Learn about arrays and how to work with collections of data.

Learn more