Intermediate · JavaScript in depth · topic 31 of 64 · 30 min
Strings in depth
Explanation
Template literals
const name = 'Meena';
const amount = 250;
const msg = `Hi ${name}, you paid Rs ${amount}.`;
const gst = `GST: Rs ${amount * 0.18}`; // any expression works inside ${}
const receipt = `Order: A101
Items: 3
Total: Rs 750`; // keeps the line breaksCharacters and positions
const city = 'Bengaluru';
city.length; // 9
city[0]; // 'B'
city.at(-1); // 'u' (a negative number counts from the end)
city.slice(0, 4); // 'Beng' (from index 0 up to, not including, 4)
city.slice(-3); // 'uru' (the last 3 characters)
city.indexOf('g'); // 3Cleaning and checking text
| Method | Example | Result |
|---|---|---|
| trim() | ' Pune '.trim() | 'Pune' |
| toUpperCase() | 'upi'.toUpperCase() | 'UPI' |
| toLowerCase() | 'Delhi'.toLowerCase() | 'delhi' |
| includes(x) | 'masala chai'.includes('chai') | true |
| startsWith(x) | '+919876543210'.startsWith('+91') | true |
| endsWith(x) | 'photo.jpg'.endsWith('.jpg') | true |
| replace(a, b) | 'a-b-c'.replace('-', '+') | 'a+b-c' (first one only) |
| replaceAll(a, b) | 'a-b-c'.replaceAll('-', '+') | 'a+b+c' |
| padStart(n, ch) | '7'.padStart(3, '0') | '007' |
| repeat(n) | '*'.repeat(6) | '******' |
Splitting and joining
const list = 'rice,dal,oil';
const items = list.split(','); // ['rice', 'dal', 'oil']
items.join(' | '); // 'rice | dal | oil'
const words = ' learn web dev '.trim().split(' ').filter(Boolean);
// ['learn', 'web', 'dev'] filter(Boolean) drops the empty strings
const slug = 'JavaScript In Depth'.toLowerCase().split(' ').join('-');
// 'javascript-in-depth'Comparing strings
=== compares exactly, so "Pune" === "pune" is false. To ignore capitals, compare lower-case copies. The < and > operators compare character codes, where every capital letter comes before every small letter. That is why sorting names without help puts "Zoya" before "arjun".
'Pune'.toLowerCase() === 'pune'; // true
['b', 'a', 'C'].sort(); // ['C', 'a', 'b'] capitals first
['b', 'a', 'C'].sort((x, y) => x.localeCompare(y)); // ['a', 'b', 'C']
'apple'.localeCompare('banana'); // a negative number: apple comes firstMoney: rupees the Indian way
In India, big numbers are grouped in lakhs and crores: 1,00,000 is one lakh and 1,00,00,000 is one crore. Intl.NumberFormat (Intl is short for internationalisation) formats numbers for a language and region. The locale "en-IN" means English as used in India.
const inr = new Intl.NumberFormat('en-IN', { style: 'currency', currency: 'INR' });
inr.format(100000); // '₹1,00,000.00'
inr.format(2499.5); // '₹2,499.50'
new Intl.NumberFormat('en-IN').format(12345678); // '1,23,45,678'
(199.999).toFixed(2); // '200.00' a string with 2 decimals
(0.1 + 0.2).toFixed(2); // '0.30'Strings are immutable
let name = 'ravi';
name[0] = 'R'; // does nothing
name.toUpperCase(); // returns 'RAVI', but name is unchanged
console.log(name); // 'ravi'
name = name[0].toUpperCase() + name.slice(1); // store the new string
console.log(name); // 'Ravi'Watch the lesson
Strings in depth · 1/7
const msg = `Hi ${name}, you paid Rs ${amount}`;Template literals use backticks. Put any value or sum inside dollar and curly braces.
Prefer a video by a teacher? Find free videos on “javascript string methods template literals slice split tutorial” on YouTube ↗
In real life: A UPI payment receipt
After a UPI payment, the app shows "Paid ₹1,250.00 to Sharma Kirana" with the time. Behind it, a template literal builds the sentence and Intl.NumberFormat with "en-IN" formats the amount. The UPI ID you typed was cleaned with trim and toLowerCase before it was checked, and your bank account number is shown as "XXXXXX4321" using slice(-4) and padStart.
Practice (0/3 done)
Write a function initials(fullName) that returns the first letter of each word, in capitals. Extra spaces must not break it. Example: initials("ravi kumar sharma") returns "RKS" and initials(" asha devi ") returns "AD".
Write a function maskNumber(number) that hides all but the last 4 characters of a string with "X". The result has the same length as the input. Example: maskNumber("9876543210") returns "XXXXXX3210". Use slice(-4) and padStart.
Write a function formatRupees(amount) that returns the amount as Indian rupees using Intl.NumberFormat with the locale "en-IN", style "currency" and currency "INR". Example: formatRupees(100000) returns "₹1,00,000.00" and formatRupees(49.5) returns "₹49.50".
Quick quiz
Read more (free)
Pass the quiz (60% or more) or mark this topic as done when you are ready.
Your progress is saved on this device only.