JavaScript course menu
JavaScript Strings: Template Literals, Methods, Slicing and Searching
Learn JavaScript strings: quotes and escapes, template literals with ${}, length and indexes, slice and substring, searching with includes, indexOf, startsWith and endsWith, changing case, trim, replace and replaceAll, split and join, padStart and repeat.
On this page
Strings hold text: names, messages, URLs, whole documents. JavaScript strings come with dozens of built-in methods.
Creating strings#
Single quotes, double quotes and backticks all create strings:
const a = 'single quotes';
const b = "double quotes";
const c = `backticks (template literal)`;
console.log(a, "|", b, "|", c);single quotes | double quotes | backticks (template literal)Single and double quotes behave the same; pick one style and use it consistently. To put the same quote inside a string, escape it with a backslash, or use the other kind of quote:
console.log('It\'s raining');
console.log("She said \"hi\"");
console.log("Line one\nLine two");
console.log("Tab\tseparated");It's raining
She said "hi"
Line one
Line two
Tab separated\n is a new line, \t a tab, and \\ a backslash.
Template literals#
Backtick strings can contain placeholders with ${...}, which insert the value of any expression:
const name = "Asha";
const items = 3;
const price = 49.5;
console.log(`Hi ${name}, you bought ${items} items.`);
console.log(`Total: ₹${(items * price).toFixed(2)}`);
console.log(`Status: ${items > 2 ? "free delivery" : "standard delivery"}`);Hi Asha, you bought 3 items.
Total: ₹148.50
Status: free deliveryThey can also span several lines without \n:
const receipt = `Item: Notebook
Qty: 2
Paid: Yes`;
console.log(receipt);Item: Notebook
Qty: 2
Paid: YesTemplate literals are usually clearer than joining with +.
Length and characters#
const word = "JavaScript";
console.log(word.length);
console.log(word[0]);
console.log(word[word.length - 1]);
console.log(word.at(-1));
console.log(word[50]);10
J
t
t
undefinedIndexes start at 0. at(-1) counts from the end. A missing index gives undefined, not an error.
Strings are immutable: word[0] = "j" does nothing. Every method below returns a new string.
Changing case and trimming#
const input = " Hello World ";
console.log(`[${input.trim()}]`);
console.log(input.trim().toUpperCase());
console.log(input.trim().toLowerCase());
console.log(`[${input.trimStart()}]`);[Hello World]
HELLO WORLD
hello world
[Hello World ]trim() is essential when processing user input.
Searching#
const email = "asha.rao@example.com";
console.log(email.includes("@"));
console.log(email.startsWith("asha"));
console.log(email.endsWith(".com"));
console.log(email.indexOf("@"));
console.log(email.indexOf("xyz"));true
true
true
8
-1indexOf returns the position of the first match, or -1 if there is none.
Extracting parts: slice#
slice(start, end) returns the part from start up to, but not including, end:
const email = "asha.rao@example.com";
const at = email.indexOf("@");
console.log(email.slice(0, at));
console.log(email.slice(at + 1));
console.log(email.slice(-4));asha.rao
example.com
.comNegative numbers count from the end. (substring is similar but does not accept negative numbers; slice is usually the better choice.)
Replacing#
const text = "I like tea. Tea is great.";
console.log(text.replace("tea", "coffee"));
console.log(text.replaceAll("ea", "EA"));
console.log(text.replace(/tea/gi, "coffee"));I like coffee. Tea is great.
I like tEA. TEA is grEAt.
I like coffee. coffee is great.replace with a string replaces only the first match; replaceAll replaces every match. The last line uses a regular expression with the g (global) and i (ignore case) flags.
Splitting and joining#
split turns a string into an array; join turns an array back into a string:
const csv = "mango,banana,guava";
const fruits = csv.split(",");
console.log(fruits);
console.log(fruits.join(" | "));
console.log("hello".split(""));[ 'mango', 'banana', 'guava' ]
mango | banana | guava
[ 'h', 'e', 'l', 'l', 'o' ]Padding and repeating#
console.log("7".padStart(3, "0"));
console.log("Total".padEnd(10, ".") + "₹450");
console.log("=".repeat(20));007
Total.....₹450
====================Comparing strings#
=== compares strings exactly, including case. For case-insensitive comparison, convert both to the same case first. localeCompare sorts text correctly for a language:
console.log("apple" === "Apple");
console.log("apple".toLowerCase() === "Apple".toLowerCase());
console.log(["banana", "Apple", "cherry"].sort((a, b) => a.localeCompare(b)));false
true
[ 'Apple', 'banana', 'cherry' ]Practice#
Practice exercise
Given const fullName = " asha RAO ";, print it as Asha Rao (trimmed, each word capitalised), then print its initials A.R..
Show solution
const fullName = " asha RAO ";
const words = fullName.trim().toLowerCase().split(" ");
const capitalised = words.map((w) => w[0].toUpperCase() + w.slice(1));
console.log(capitalised.join(" "));
console.log(capitalised.map((w) => w[0] + ".").join(""));Asha Rao
A.R.map applies a function to every item of an array; you will learn it properly in Array Methods.
Key takeaway#
Finished this lesson?