Skip to content
Laviyx Learn

Try

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.

Beginner9 min readUpdated
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:

JavaScript
const a = 'single quotes';
const b = "double quotes";
const c = `backticks (template literal)`;
console.log(a, "|", b, "|", c);
Output
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:

JavaScript
console.log('It\'s raining');
console.log("She said \"hi\"");
console.log("Line one\nLine two");
console.log("Tab\tseparated");
Output
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:

JavaScript
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"}`);
Output
Hi Asha, you bought 3 items.
Total: ₹148.50
Status: free delivery

They can also span several lines without \n:

JavaScript
const receipt = `Item: Notebook
Qty: 2
Paid: Yes`;
console.log(receipt);
Output
Item: Notebook
Qty: 2
Paid: Yes

Template literals are usually clearer than joining with +.

Length and characters#

JavaScript
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]);
Output
10
J
t
t
undefined

Indexes 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#

JavaScript
const input = "   Hello World   ";
console.log(`[${input.trim()}]`);
console.log(input.trim().toUpperCase());
console.log(input.trim().toLowerCase());
console.log(`[${input.trimStart()}]`);
Output
[Hello World]
HELLO WORLD
hello world
[Hello World   ]

trim() is essential when processing user input.

Searching#

JavaScript
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"));
Output
true
true
true
8
-1

indexOf 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:

JavaScript
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));
Output
asha.rao
example.com
.com

Negative numbers count from the end. (substring is similar but does not accept negative numbers; slice is usually the better choice.)

Replacing#

JavaScript
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"));
Output
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:

JavaScript
const csv = "mango,banana,guava";
const fruits = csv.split(",");
console.log(fruits);
console.log(fruits.join(" | "));
console.log("hello".split(""));
Output
[ 'mango', 'banana', 'guava' ]
mango | banana | guava
[ 'h', 'e', 'l', 'l', 'o' ]

Padding and repeating#

JavaScript
console.log("7".padStart(3, "0"));
console.log("Total".padEnd(10, ".") + "₹450");
console.log("=".repeat(20));
Output
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:

JavaScript
console.log("apple" === "Apple");
console.log("apple".toLowerCase() === "Apple".toLowerCase());
console.log(["banana", "Apple", "cherry"].sort((a, b) => a.localeCompare(b)));
Output
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
JavaScript
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(""));
Output
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?