2. Strings in JavaScript
Strings are one of the most fundamental data types in JavaScript. They represent text and are used everywhere—from displaying messages to handling user input and manipulating data. Mastering strings means you can process, validate, and transform text with ease.
2.1 String Basics
Creating Strings
You can create strings using single quotes, double quotes, or backticks (template literals):
let single = 'Hello';
let double = "World";
let template = `Hello, World!`;
Best Practice: Use backticks for dynamic strings and multi-line text.
Accessing Characters
Strings are zero-indexed:
let str = 'JavaScript';
console.log(str[0]); // 'J'
console.log(str.charAt(4)); // 'S'
2.2 String Methods
JavaScript provides many built-in methods for working with strings. Here are the most useful ones, with practical examples:
slice() – Extract a Portion
let text = 'abcdef';
console.log(text.slice(1, 4)); // 'bcd'
split() – Convert to Array
let csv = 'red,green,blue';
let colors = csv.split(',');
// ['red', 'green', 'blue']
replace() – Substitute Text
let msg = 'I like cats.';
let newMsg = msg.replace('cats', 'dogs');
// 'I like dogs.'
includes() – Check for Substring
let phrase = 'JavaScript is awesome';
console.log(phrase.includes('awesome')); // true
Template Strings (${}) – Dynamic & Multi-line
Template literals (backticks) allow embedded expressions and multi-line strings:
let name = 'Sam';
let greeting = `Hello, ${name}!`;
// 'Hello, Sam!'
let multi = `Line 1
Line 2`;
2.3 More Useful String Methods
toUpperCase(),toLowerCase()trim()– Remove whitespacestartsWith(),endsWith()indexOf(),lastIndexOf()
let messy = ' spaced ';
console.log(messy.trim()); // 'spaced'
console.log('abc'.toUpperCase()); // 'ABC'
console.log('hello.js'.endsWith('.js')); // true
2.4 Immutability & Performance
Strings in JavaScript are immutable—methods return new strings, they do not modify the original.
let s = 'abc';
let t = s.toUpperCase();
console.log(s); // 'abc'
console.log(t); // 'ABC'
Tip: For heavy string manipulation, consider using arrays and join() for better performance.
Next: Conditionals & Loops