JavaScript Mastery - Strings


Introduction to Strings
In JavaScript, a string is a sequence of characters used to represent text data. Strings are one of the primitive data types and are fundamental to web development. They are enclosed in either single quotes ('
), double quotes ("
), or backticks (`
) for template literals. Strings in JavaScript are immutable, meaning once created, their characters cannot be changed directly - any operation that appears to modify a string actually creates a new string.
let singleQuote = 'Hello World';
let doubleQuote = "Hello World";
let templateLiteral = `Hello World`;
String Properties and Methods
1. Length Property
The length
property returns the number of characters in a string, including spaces and special characters. This property is essential for iteration and string manipulation operations.
Syntax:
string.length
Example:
let fullname = 'Vitthal korvan';
console.log(fullname.length); // 14
console.log(fullname[fullname.length - 1]); // 'n' (last character)
Practice Questions:
Q1: What will be the output of the following code?
let str = "JavaScript";
console.log(str.length);
Answer: 10
- The string "JavaScript" has 10 characters.
Q2: How do you access the last character of a string using the length property?
let text = "Programming";
console.log(text[text.length - 1]);
Answer: 'g'
- We use text.length - 1
because array indexing starts from 0.
Q3: What is the length of an empty string?
let empty = "";
console.log(empty.length);
Answer: 0
- An empty string has no characters, so its length is 0.
2. charAt() Method
The charAt()
method returns the character at a specified index in a string. If the index is out of range, it returns an empty string instead of undefined.
Syntax:
string.charAt(index)
Example:
let str = "Hello, World!";
console.log(str.charAt(0)); // 'H'
console.log(str.charAt(7)); // 'W'
console.log(str.charAt(str.length - 1)); // '!'
Practice Questions:
Q1: What will "Hello".charAt(1)
return? Answer: 'e'
- The character at index 1 is 'e'.
Q2: What happens when you use charAt() with an index that doesn't exist?
let str = "Hello";
console.log(str.charAt(10));
Answer: ''
(empty string) - charAt() returns an empty string for invalid indices.
Q3: How is charAt() different from bracket notation?
let str = "Hello";
console.log(str.charAt(10)); // vs str[10]
Answer: charAt(10)
returns an empty string ''
, while str[10]
returns undefined
.
3. concat() Method
The concat()
method joins two or more strings together and returns a new string. It doesn't modify the original strings but creates a new concatenated string.
Syntax:
string.concat(string1, string2, ..., stringN)
Example:
let str1 = "Hello";
let str2 = "World";
let str3 = "!";
console.log(str1.concat(", ", str2, str3)); // "Hello, World!"
console.log("".concat(str1, " ", str2)); // "Hello World"
Practice Questions:
Q1: What will be the result of concatenating three strings?
let a = "Java";
let b = "Script";
let c = "!";
console.log(a.concat(b, c));
Answer: "JavaScript!"
- All strings are joined together in order.
Q2: Can you use concat() with non-string values?
let str = "Number: ";
console.log(str.concat(42, " and ", true));
Answer: "Number: 42 and true"
- Non-string values are converted to strings.
Q3: How does concat() compare to the + operator?
let result1 = "Hello".concat(" ", "World");
let result2 = "Hello" + " " + "World";
Answer: Both produce "Hello World"
, but the + operator is more commonly used and often more readable.
4. includes() Method
The includes()
method checks whether a string contains a specified substring. It returns true if the substring is found, false otherwise. The search is case-sensitive.
Syntax:
string.includes(searchString, startPosition)
Example:
let sentence = "The quick brown fox jumps over the lazy dog.";
console.log(sentence.includes("quick")); // true
console.log(sentence.includes("Quick")); // false (case-sensitive)
console.log(sentence.includes("lazy", 30)); // true
Practice Questions:
Q1: What will this code output?
let text = "JavaScript is awesome";
console.log(text.includes("Script"));
Answer: true
- "Script" is found within "JavaScript".
Q2: How does the second parameter work in includes()?
let str = "Hello Hello World";
console.log(str.includes("Hello", 6));
Answer: true
- Search starts from index 6, finds the second "Hello".
Q3: Is the includes() method case-sensitive?
let str = "Hello World";
console.log(str.includes("hello"));
Answer: false
- includes() is case-sensitive, so "hello" doesn't match "Hello".
5. indexOf() Method
The indexOf()
method returns the index of the first occurrence of a specified substring. If the substring is not found, it returns -1. This method performs a case-sensitive search.
Syntax:
string.indexOf(searchValue, startPosition)
Example:
let sentence = "The quick brown fox jumps over the lazy dog.";
console.log(sentence.indexOf("quick")); // 4
console.log(sentence.indexOf("fox")); // 16
console.log(sentence.indexOf("cat")); // -1
Practice Questions:
Q1: What index will be returned for the first occurrence?
let str = "Hello Hello World";
console.log(str.indexOf("Hello"));
Answer: 0
- Returns the index of the first occurrence.
Q2: What does indexOf() return when the substring is not found?
let str = "JavaScript";
console.log(str.indexOf("Python"));
Answer: -1
- Indicates the substring was not found.
Q3: How can you find all occurrences of a substring?
let str = "Hello Hello Hello";
let index = str.indexOf("Hello");
console.log(index); // First occurrence
console.log(str.indexOf("Hello", index + 1)); // Second occurrence
Answer: First: 0
, Second: 6
- Use the second parameter to continue searching from the next position.
6. slice() Method
The slice()
method extracts a section of a string and returns it as a new string. It accepts start and end parameters, where the end index is exclusive. Negative indices count from the end of the string.
Syntax:
string.slice(startIndex, endIndex)
Example:
let sentence = "The quick brown fox jumps over the lazy dog.";
console.log(sentence.slice(4, 9)); // "quick"
console.log(sentence.slice(16)); // "fox jumps over the lazy dog."
console.log(sentence.slice(-9, -3)); // "lazy d"
Practice Questions:
Q1: What will be extracted from this slice operation?
let str = "JavaScript";
console.log(str.slice(0, 4));
Answer: "Java"
- Extracts from index 0 to 3 (4 is exclusive).
Q2: How do negative indices work in slice()?
let str = "Programming";
console.log(str.slice(-4, -1));
Answer: "min"
- Negative indices count from the end: -4 is 'a', -1 is 'g' (exclusive).
Q3: What happens when you omit the second parameter?
let str = "Hello World";
console.log(str.slice(6));
Answer: "World"
- Extracts from index 6 to the end of the string.
7. split() Method
The split()
method divides a string into an array of substrings based on a specified separator. It's commonly used to break strings into manageable parts for processing.
Syntax:
string.split(separator, limit)
Example:
let sentence = "The quick brown fox jumps over the lazy dog.";
console.log(sentence.split(" "));
// ["The", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog."]
console.log(sentence.split(" ", 3));
// ["The", "quick", "brown"]
console.log(sentence.split("o"));
// ["The quick br", "wn f", "x jumps ", "ver the lazy d", "g."]
Practice Questions:
Q1: How do you split a string into individual characters?
let str = "Hello";
console.log(str.split(""));
Answer: ["H", "e", "l", "l", "o"]
- Using an empty string as separator splits into characters.
Q2: What does the limit parameter do in split()?
let str = "a,b,c,d,e";
console.log(str.split(",", 3));
Answer: ["a", "b", "c"]
- Limits the result to the first 3 elements.
Q3: What happens when the separator is not found?
let str = "Hello World";
console.log(str.split("x"));
Answer: ["Hello World"]
- Returns an array with the original string as the only element.
8. toLowerCase() and toUpperCase() Methods
These methods convert strings to lowercase and uppercase respectively. They return new strings without modifying the original string, making them safe for use in any context.
Syntax:
string.toLowerCase()
string.toUpperCase()
Example:
let sentence = "The Quick Brown Fox.";
console.log(sentence.toLowerCase()); // "the quick brown fox."
console.log(sentence.toUpperCase()); // "THE QUICK BROWN FOX."
console.log("JavaScript".toLowerCase()); // "javascript"
console.log("hello world".toUpperCase()); // "HELLO WORLD"
Practice Questions:
Q1: How do you perform case-insensitive string comparison?
let str1 = "Hello";
let str2 = "HELLO";
console.log(str1.toLowerCase() === str2.toLowerCase());
Answer: true
- Converting both to lowercase allows case-insensitive comparison.
Q2: Do these methods modify the original string?
let original = "JavaScript";
let lower = original.toLowerCase();
console.log(original); // What will this show?
Answer: "JavaScript"
- The original string remains unchanged because strings are immutable.
Q3: What happens with mixed case strings?
let mixed = "JaVaScRiPt";
console.log(mixed.toUpperCase());
console.log(mixed.toLowerCase());
Answer: "JAVASCRIPT"
and "javascript"
respectively - All characters are converted regardless of their original case.
9. trim() Method
The trim()
method removes whitespace characters from both ends of a string. It's particularly useful for cleaning user input and removing unwanted spaces that might affect string operations.
Syntax:
string.trim()
Example:
let greeting = " Hello, World! ";
console.log(greeting.trim()); // "Hello, World!"
console.log(" Hello".trim()); // "Hello"
console.log("World! ".trim()); // "World!"
Practice Questions:
Q1: What types of whitespace does trim() remove?
let str = "\n\t Hello World \r\n";
console.log(str.trim());
Answer: "Hello World"
- Removes spaces, tabs, newlines, and carriage returns from both ends.
Q2: Does trim() remove spaces from the middle of a string?
let str = " Hello World ";
console.log(str.trim());
Answer: "Hello World"
- Only removes whitespace from the beginning and end, not the middle.
Q3: How do you remove whitespace from only one side?
let str = " Hello World ";
console.log(str.trimStart()); // or trimLeft()
console.log(str.trimEnd()); // or trimRight()
Answer: "Hello World "
and " Hello World"
respectively - Use trimStart() or trimEnd() for one-sided trimming.
10. replace() and replaceAll() Methods
The replace()
method replaces the first occurrence of a specified value with a new value. The replaceAll()
method replaces all occurrences. Both return a new string without modifying the original.
Syntax:
string.replace(searchValue, newValue)
string.replaceAll(searchValue, newValue)
Example:
let sentence = "The quick brown fox jumps over the lazy dog.";
console.log(sentence.replace("fox", "cat"));
// "The quick brown cat jumps over the lazy dog."
console.log(sentence.replace(/dog/i, "elephant"));
// "The quick brown fox jumps over the lazy elephant."
console.log(sentence.replaceAll(" ", "-"));
// "The-quick-brown-fox-jumps-over-the-lazy-dog."
Practice Questions:
Q1: What's the difference between replace() and replaceAll()?
let str = "Hello Hello World";
console.log(str.replace("Hello", "Hi"));
console.log(str.replaceAll("Hello", "Hi"));
Answer: "Hi Hello World"
and "Hi Hi World"
- replace() only replaces the first occurrence, replaceAll() replaces all.
Q2: How can you replace all occurrences using only replace()?
let str = "cat and cat and cat";
console.log(str.replace(/cat/g, "dog"));
Answer: "dog and dog and dog"
- Use a global regular expression with the /g flag.
Q3: Can you use replace() with a function?
let str = "Hello World";
console.log(str.replace(/\w+/g, function(match) {
return match.toUpperCase();
}));
Answer: "HELLO WORLD"
- The function receives each match and returns the replacement value.
11. startsWith() and endsWith() Methods
These methods check if a string starts or ends with specified characters. They return boolean values and are case-sensitive, making them useful for validation and filtering operations.
Syntax:
string.startsWith(searchString, position)
string.endsWith(searchString, length)
Example:
let originalString = "hello world";
console.log(originalString.startsWith("hello")); // true
console.log(originalString.endsWith("world")); // true
console.log(originalString.startsWith("Hello")); // false (case-sensitive)
Practice Questions:
Q1: How do you check for multiple possible beginnings?
let url = "https://example.com";
console.log(url.startsWith("http://") || url.startsWith("https://"));
Answer: true
- Use logical OR to check multiple possibilities.
Q2: What does the second parameter do in startsWith()?
let str = "JavaScript Programming";
console.log(str.startsWith("Script", 4));
Answer: true
- The second parameter specifies where to start checking from.
Q3: How can you make these methods case-insensitive?
let str = "Hello World";
console.log(str.toLowerCase().startsWith("hello"));
Answer: true
- Convert the string to lowercase before checking.
12. Additional Utility Methods
padStart() and padEnd(): These methods pad a string to a specified length with another string.
const originalString = "hello";
console.log(originalString.padStart(10, "*")); // "*****hello"
console.log(originalString.padEnd(10, "*")); // "hello*****"
repeat(): This method repeats a string a specified number of times.
const originalString = "hello";
console.log(originalString.repeat(3)); // "hellohellohello"
Practical String Applications
String Iteration and Character Access
Strings can be accessed character by character using various methods:
let fullname = 'Vitthal korvan';
// Using for loop with bracket notation
for(let i = 0; i < fullname.length; i++){
console.log(fullname[i]);
}
// Using for...of loop
for(let char of fullname){
console.log(char);
}
String Reversal Algorithm
Here's a common algorithm to reverse a string:
function reverseString(str) {
let reversed = "";
for(let i = str.length - 1; i >= 0; i--){
reversed += str[i];
}
return reversed;
}
console.log(reverseString("JavaScript")); // "tpircSavaJ"
Anagram Detection
An anagram is a word formed by rearranging letters of another word:
function isAnagram(str1, str2) {
// Remove spaces and convert to lowercase
str1 = str1.replace(/\s/g, '').toLowerCase();
str2 = str2.replace(/\s/g, '').toLowerCase();
// Check if lengths are equal
if(str1.length !== str2.length) return false;
// Sort characters and compare
return str1.split('').sort().join('') === str2.split('').sort().join('');
}
console.log(isAnagram("listen", "silent")); // true
console.log(isAnagram("hello", "world")); // false
Comprehensive Practice Problems
Problem 1: Character Frequency Counter
Write a function that counts the frequency of each character in a string.
function charFrequency(str) {
const freq = {};
for(let char of str.toLowerCase()) {
if(char !== ' ') {
freq[char] = (freq[char] || 0) + 1;
}
}
return freq;
}
console.log(charFrequency("Hello World"));
// Output: {h: 1, e: 1, l: 3, o: 2, w: 1, r: 1, d: 1}
Problem 2: Palindrome Checker
Create a function to check if a string is a palindrome.
function isPalindrome(str) {
const cleaned = str.replace(/[^a-zA-Z0-9]/g, '').toLowerCase();
return cleaned === cleaned.split('').reverse().join('');
}
console.log(isPalindrome("A man a plan a canal Panama")); // true
console.log(isPalindrome("race a car")); // false
Problem 3: Word Count Function
Develop a function that counts words in a sentence.
function wordCount(sentence) {
return sentence.trim().split(/\s+/).filter(word => word.length > 0).length;
}
console.log(wordCount(" Hello world JavaScript ")); // 3
console.log(wordCount("")); // 0
Best Practices and Tips
String Immutability: Remember that strings are immutable in JavaScript. Methods like
replace()
,toUpperCase()
, etc., return new strings.Performance Considerations: For multiple string concatenations, consider using an array with
join()
instead of repeated+
operations.Template Literals: Use template literals (backticks) for complex string formatting:
const name = "JavaScript"; const message = `Welcome to ${name} programming!`;
Regular Expressions: For complex string operations, regular expressions can be more efficient than multiple string method calls.
Input Validation: Always validate and sanitize string inputs, especially user data.
Subscribe to my newsletter
Read articles from Code Subtle directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Code Subtle
Code Subtle
At Code Subtle, we empower aspiring web developers through personalized mentorship and engaging learning resources. Our community bridges the gap between theory and practice, guiding students from basics to advanced concepts. We offer expert mentorship and write interactive, user-friendly articles on all aspects of web development. Join us to learn, grow, and build your future in tech!