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).
1// Using single quotes2let firstName = 'John';34// Using double quotes5let lastName = "Doe";67// Using backticks (template literals - ES6)8let greeting = `Hello, ${firstName} ${lastName}!`;910console.log(greeting); // Outputs: Hello, John Doe!1112// Strings with quotes inside13let singleInDouble = "It's a beautiful day"; // Single quote inside double quotes14let doubleInSingle = 'He said, "Hello!"'; // Double quotes inside single quotes15let escapeQuotes = 'It\'s a beautiful day'; // Escaping with backslash1617// Empty string18let emptyString = "";1920// 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.
1// String length2let message = "Hello, World!";3console.log(message.length); // Outputs: 13 (counts all characters including spaces and punctuation)45// Checking if a string is empty6let emptyString = "";7let isEmptyUsingLength = emptyString.length === 0; // true8let 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.
1// Accessing characters by index2let greeting = "Hello";34console.log(greeting[0]); // Outputs: "H"5console.log(greeting[1]); // Outputs: "e"6console.log(greeting[4]); // Outputs: "o"78// Trying to access an index that doesn't exist9console.log(greeting[5]); // Outputs: undefined1011// Strings are immutable (cannot be changed)12greeting[0] = "J"; // This does nothing13console.log(greeting); // Still outputs: "Hello"1415// Getting the last character16let lastChar = greeting[greeting.length - 1]; // "o"1718// 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.
// This doesn't worklet name = "John";name[0] = "T"; // No effectconsole.log(name); // Still "John"// This worksname = "T" + name.substring(1); // Create a new stringconsole.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
1// Converting case2let message = "Hello, World!";34console.log(message.toUpperCase()); // "HELLO, WORLD!"5console.log(message.toLowerCase()); // "hello, world!"67// Original string remains unchanged8console.log(message); // "Hello, World!"910// Practical example: Case-insensitive comparison11let userInput = "JavaScript";12let storedValue = "javascript";1314if (userInput.toLowerCase() === storedValue.toLowerCase()) {15 console.log("The values match (ignoring case)!");16}
Finding Substrings
1// Checking if a string contains a substring2let sentence = "JavaScript is fun to learn";34// indexOf returns the position of the first occurrence (-1 if not found)5console.log(sentence.indexOf("Script")); // 46console.log(sentence.indexOf("Java")); // 07console.log(sentence.indexOf("Python")); // -1 (not found)89// lastIndexOf returns the position of the last occurrence10let repeatedText = "hello hello hello";11console.log(repeatedText.lastIndexOf("hello")); // 121213// includes returns true if the string contains the substring (ES6)14console.log(sentence.includes("fun")); // true15console.log(sentence.includes("boring")); // false1617// startsWith and endsWith (ES6)18console.log(sentence.startsWith("Java")); // true19console.log(sentence.endsWith("learn")); // true2021// Checking with specific position22console.log(sentence.startsWith("Script", 4)); // true (start checking from index 4)
Extracting Substrings
1// Extracting parts of a string2let message = "Hello, World!";34// 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)1011// substring(start, end) - similar to slice but doesn't support negative indices12console.log(message.substring(0, 5)); // "Hello"13console.log(message.substring(7, 12)); // "World"1415// substr(start, length) - extracts length characters from start16// Note: substr() is deprecated, but still works17console.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)
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
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
1// Replacing content in strings2let message = "Hello, World!";34// replace() - replaces the first occurrence5let newMessage = message.replace("Hello", "Hi");6console.log(newMessage); // "Hi, World!"78// replace() only replaces the first occurrence by default9let text = "apple apple apple";10console.log(text.replace("apple", "orange")); // "orange apple apple"1112// To replace all occurrences (ES2021 and later)13console.log(text.replaceAll("apple", "orange")); // "orange orange orange"1415// For older browsers, use regular expression with global flag16console.log(text.replace(/apple/g, "orange")); // "orange orange orange"1718// replace() is case-sensitive19let caseSensitive = "Hello hello";20console.log(caseSensitive.replace("hello", "hi")); // "Hello hi"2122// Use regular expression with 'i' flag for case-insensitive replace23console.log(caseSensitive.replace(/hello/i, "hi")); // "hi hello"24console.log(caseSensitive.replace(/hello/gi, "hi")); // "hi hi" (global + case-insensitive)
Trimming Whitespace
1// Trimming whitespace2let text = " Hello, World! ";34// trim() removes whitespace from both ends5console.log(text.trim()); // "Hello, World!"67// trimStart() / trimLeft() removes whitespace from the start8console.log(text.trimStart()); // "Hello, World! "910// trimEnd() / trimRight() removes whitespace from the end11console.log(text.trimEnd()); // " Hello, World!"1213// Practical example: Cleaning user input14function validateUsername(username) {15 const trimmedUsername = username.trim();16 return trimmedUsername.length >= 3;17}1819console.log(validateUsername(" john ")); // true20console.log(validateUsername(" jo ")); // false
Padding and Alignment
1// Padding strings (ES2017)2let number = "42";34// padStart(targetLength, padString) adds padding at the start5console.log(number.padStart(5, "0")); // "00042"6console.log(number.padStart(8, "x")); // "xxxxxx42"78// padEnd(targetLength, padString) adds padding at the end9console.log(number.padEnd(5, "0")); // "42000"10console.log(number.padEnd(8, "!")); // "42!!!!!!"1112// Practical example: Formatting credit card13let cardNumber = "1234567890123456";14let lastFour = cardNumber.slice(-4);15let maskedCard = lastFour.padStart(16, "*");16console.log(maskedCard); // "************3456"
Splitting and Joining
1// Splitting strings into arrays2let sentence = "JavaScript is fun to learn";34// split(separator) creates an array by splitting the string5let words = sentence.split(" ");6console.log(words); // ["JavaScript", "is", "fun", "to", "learn"]78// Split by other characters9let csvData = "John,Doe,30,New York";10let dataArray = csvData.split(",");11console.log(dataArray); // ["John", "Doe", "30", "New York"]1213// Limit the number of splits14let limitedSplit = sentence.split(" ", 3);15console.log(limitedSplit); // ["JavaScript", "is", "fun"]1617// Split into characters18let chars = "Hello".split("");19console.log(chars); // ["H", "e", "l", "l", "o"]2021// Joining arrays into strings22let wordsArray = ["JavaScript", "is", "awesome"];23let joinedString = wordsArray.join(" ");24console.log(joinedString); // "JavaScript is awesome"2526// Join with different separators27console.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.
1// Basic template literal with variable interpolation2let name = "Alice";3let greeting = `Hello, ${name}!`;4console.log(greeting); // "Hello, Alice!"56// Expressions in template literals7let a = 5;8let b = 10;9console.log(`The sum of ${a} and ${b} is ${a + b}`); // "The sum of 5 and 10 is 15"1011// Multiline strings12let multiline = `This is a string13that spans multiple14lines without special characters.`;1516console.log(multiline);17// Outputs:18// This is a string19// that spans multiple20// lines without special characters.2122// 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}3334let language = "JavaScript";35let years = 25;3637let 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.
1// Basic comparison2console.log("apple" === "apple"); // true3console.log("Apple" === "apple"); // false (case-sensitive)45// Case-insensitive comparison6console.log("Apple".toLowerCase() === "apple".toLowerCase()); // true78// Comparing alphabetical order9console.log("apple" < "banana"); // true (a comes before b)10console.log("apple" > "Apple"); // true (lowercase comes after uppercase in ASCII/Unicode)1112// localeCompare for proper alphabetical comparison13console.log("apple".localeCompare("banana")); // -1 (comes before)14console.log("banana".localeCompare("apple")); // 1 (comes after)15console.log("apple".localeCompare("apple")); // 0 (same)1617// Locale-aware comparison18console.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 Sequence | Character | Example |
---|---|---|
\' | Single quote | 'It\'s raining' |
\" | Double quote | "She said, \"Hello\"" |
\\ | Backslash | "C:\\Files\\Document" |
\n | New line | "Line 1\nLine 2" |
\t | Tab | "Name:\tJohn" |
\r | Carriage return | "Text\rOverwrite" |
\b | Backspace | "Hello\b" |
1// Escape sequences examples2console.log("This is a line\nThis is another line");3// Outputs:4// This is a line5// This is another line67console.log("Name:\tJohn\tAge:\t30");8// Outputs: Name: John Age: 30910console.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.
1// Counting occurrences of a substring2function countOccurrences(str, subStr) {3 let count = 0;4 let position = str.indexOf(subStr);56 while (position !== -1) {7 count++;8 position = str.indexOf(subStr, position + 1);9 }1011 return count;12}1314console.log(countOccurrences("banana", "a")); // 31516// Reversing a string17function reverseString(str) {18 return str.split("").reverse().join("");19}2021console.log(reverseString("hello")); // "olleh"2223// Checking if a string is a palindrome24function isPalindrome(str) {25 // Remove non-alphanumeric characters and convert to lowercase26 const cleanStr = str.replace(/[^a-zA-Z0-9]/g, "").toLowerCase();27 const reversedStr = cleanStr.split("").reverse().join("");28 return cleanStr === reversedStr;29}3031console.log(isPalindrome("A man, a plan, a canal: Panama")); // true32console.log(isPalindrome("hello")); // false3334// Capitalizing the first letter of each word35function capitalizeWords(str) {36 return str37 .split(" ")38 .map(word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())39 .join(" ");40}4142console.log(capitalizeWords("hello world")); // "Hello World"
Practice Exercises
Try these exercises to reinforce your understanding of JavaScript strings:
// 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 moreLearn how to create and use functions in JavaScript.
Learn moreLearn about arrays and how to work with collections of data.
Learn more