Strings
Creating Strings and Combining Text
String is one of the data types in JavaScript. Use it to store pieces of text, even if it's only one
character.
Create strings with single quotes, double quotes, or backticks (template literals).
Template literals let you use other variables inside ${} to create dynamic
text.
Concatenation with + lets you glue text together.
const singleQuote = 'Hello, World!';
const doubleQuote = "Hello, World!";
const templateLiteral = `Hello, World!`;
const product = 'Laptop';
const price = 999;
const discount = 99;
const total = `Total price of ${product} is ${price - discount}GBP`;
const score = 100;
let result = 'Your score is: ' + score + '.';
result += ' Congratulation!';
Key Points:
- Single quotes, double quotes, and backticks all create strings
- Template literals (backticks) let you insert values with
${} - In template literals, you can put any expression inside
${}: math, variables, functions, ternary operators, etc. - Concatenation with
+joins strings together +=adds strings to the end of existing string
String Length and Indexing
You can check how many characters are in the string, get individual characters by position.
const word = 'Bingo';
const wordLength = word.length; // 5
const big = word[0] + word[1] + word[3]; // Big
let lastChar = word[word.length - 1];
Key Points:
string.lengthtells you how many characters are in a string- Indexes of characters start at
0, so the last one is alwaysstring.length - 1 - Use
string[index]to access a specific character. Each character is also a string of length 1.
String Looping
Loop through each character using for loops.
const big = 'Big';
// Method 1: for loop with index
for (let i = 0; i < big.length; i++) {
console.log(`Index ${i}: ${big[i]}`);
}
// Method 2: for..of loop
for (let char of big) {
console.log(char);
}
Key Points:
- A
forloop gives you the index of character. You need to get the character yourself usingstring[index] for..ofloop gives you each character but without index- Common use case: count specific character in a string (vovels, numbers, etc.)
Getting parts of a string: slice() and indexOf()
Subsrtring - is a part of a string.
String has methods slice() to take substring and indexOf() to find index of a
substring inside a string.
Strings are immutable, so these methods return new strings and do not change the
original.
const fullName = "Bob Marley";
const firstName = fullName.slice(0, 3);
const lastName = fullName.slice(4);
const email = 'bob.marley@gmail.com';
const atIndex = email.indexOf("@");
const userName = email.slice(0, atIndex);
const domainName = email.slice(atIndex + 1);
const url = "https://docs.google.com";
const lastDotIndex = url.lastIndexOf(".");
const domain = url.slice(lastDotIndex + 1);
Key Points:
- Common use case: find index of some substring and then get the part of string before or after it
slice(start, end)gets substring from indexstartup to, but not including, indexendslice(start)gets substring from indexstartto the end of the stringindexOf(searchString)returns index of first occurrence ofsearchStringwithin string or-1if not foundlastIndexOf(searchString)returns index of last occurrence ofsearchStringwithin string or-1if not found- Strings are immutable, so methods like
slicecan't change the original string. They return new strings instead which you need to store in a variable.
Splitting a String into Parts: split()
Method split() breaks one string into smaller pieces and returns them as an
array of strings.
You choose where to cut by providing a separator (for example: a space
' ', a dash '-', or a comma ','). The separator itself is removed
from the result.
If you use an empty string '' as the separator, you get an array of
characters.
split() does not change the original string — it creates a new array.
const fullName = "John Doe";
const nameParts = fullName.split(' ');
const word = "Hello";
const characters = word.split('');
let date = '2024-03-15';
let parts = date.split('-');
const formatted = `${parts[1]}/${parts[2]}/${parts[0]}`;
console.log(formatted);
Key Points:
split(separator)returns an array of pieces; the original string stays the same- Pick a separator that matches your data (space for words,
-for dates,,for comma-separated values) split('')is a quick way to turn text into characters (useful for counting letters or checking each character)- Common use case: parse user input and reformat text (names, dates, tags, simple CSV)
Creating a String from an Array: join()
Method join() takes an array and combines its elements into one string.
You can choose what goes between the items by providing a separator, like
', ' for a readable list.
If you use '' (empty string) as the separator, the elements are glued together with
nothing between them.
join() does not change the array — it returns a new string.
const fruits = ['apple', 'banana', 'orange'];
const fruitsTogether = fruits.join(', ');
console.log(`I like ${fruitsTogether}`);
const chars = ['H', 'i', '!'];
const greeting = chars.join('');
Key Points:
join(separator)turns an array into one string; it does not change the original array- Use a readable separator like
', 'to display lists (names, tags, items) join('')glues pieces together with no gaps (characters, chunks of text)- Common use case: format data for UI and messages (lists, sentences, simple CSV lines)
Case Conversion: toLowerCase() and toUpperCase()
Strings are case-sensitive: "A" and "a" are different.
Methods toLowerCase() and toUpperCase() help you normalize text by converting
it to one consistent case.
This is useful when you compare user input (like emails) where letter case should not matter.
These methods return a new string, so the original value stays the same.
const userInput = 'JoHn@EmAiL.CoM';
const lower = userInput.toLowerCase();
const upper = userInput.toUpperCase();
const email1 = 'Jane.Doe@mail.com';
const email2 = 'jane.doe@mail.com';
if (email1.toLowerCase() === email2.toLowerCase()) {
console.log('Emails match!'); // This runs
}
Key Points:
- Strings are case-sensitive, so
"A" !== "a" toLowerCase()andtoUpperCase()return a new string (they don't change the original)- To compare text ignoring case, normalize both sides first
- Common use case: Compare text where case doesn't matter: emails, usernames, search terms
Searching in strings: includes(), startsWith(), and
endsWith()
Sometimes you need to know if a string contains a text, or a character.
Use includes() to check if a string contains a piece of text, and use
startsWith()/endsWith() to check the beginning or the end.
These methods return true or false, which makes them great for
if conditions.
They are also case-sensitive, so you may need to normalize with
toLowerCase().
let email = 'sarah@example.com';
const hasAtSymbol = email.includes('@'); // true
const isGmail = email.includes('gmail.com'); // false
const url = "https://google.com";
const isSecure = url.startsWith("https://"); // true
const file = "report.pdf";
const isPdf = file.endsWith(".pdf"); // true
const upload = "IMAGE.JPG";
console.log(upload.endsWith(".jpg")); // false
const normalized = upload.toLowerCase();
console.log(normalized.endsWith(".jpg")); // true
Key Points:
- Use
includes()to check if text exists anywhere in a string - Use
startsWith()for prefixes (example:https://) andendsWith()for suffixes (example: file extensions) - These methods are perfect for conditions because they return
true/false - Common use case: validate and classify user input (emails, URLs, filenames),
often after normalizing case with
toLowerCase()