Skip to content

Intermediate · JavaScript in depth · topic 31 of 64 · 30 min

Strings in depth

Explanation

A string is text. Template literals with backticks let you build text with ${} and write it over many lines. Methods such as slice, trim, split, replaceAll, padStart and includes clean and reshape text, and Intl.NumberFormat shows money the Indian way, like ₹1,00,000.00. Strings never change in place: every method gives you a new string.

Template literals

javascript
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 breaks
Backticks (the key left of 1) allow ${expressions} and many lines

Characters and positions

javascript
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'); // 3
Like arrays, string positions start at 0
Think of it like this: A string is like a row of beads on a thread, each bead a letter with a number starting from 0. slice cuts out a piece and gives you a new piece of thread. The original thread is never cut.

Cleaning and checking text

MethodExampleResult
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

javascript
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'
split turns text into an array; join turns an array into text

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".

javascript
'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 first
localeCompare compares text the way people expect
Tip: localeCompare returns a negative number, 0 or a positive number, exactly what sort wants from a compare function. Use a.name.localeCompare(b.name) whenever you sort by text.

Money: 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.

javascript
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'
Make the formatter once and reuse it for every price on the page
Careful: toFixed returns a string, not a number. "200.00" + 1 gives "200.001". Do all your maths with numbers first, and format only at the very end, when you show the value.

Strings are immutable

javascript
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'
Immutable means it cannot be changed: keep the result of a method in a variable

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)

Task 1 · Code · Javascript

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".

Task 2 · Code · Javascript

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.

Task 3 · Code · Javascript

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

Question 1

1.What is 'Hello'.slice(1, 3)?

Question 2

2.Which gives the last character of the string text?

Question 3

3.let name = 'ravi'; name.toUpperCase(); console.log(name); What is printed?

Question 4

4.Which shows 150000 as ₹1,50,000.00?

Question 5

5.How many items does 'a,b,,c'.split(',') give?

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.

← Previous: Objects in depth