String Toolbox 0/8

JavaScript basicsStrings in plain wordsOne tool at a time

String
Toolbox

A string is a piece of text, a row of characters held in quotes. This guide shows how to read it, search it, cut it up, tidy it, replace parts of it and compare it, with a small example for each that you can run.

JavaScript ES202427 tools
01

Make and read

Write text in quotes or backticks, count its characters and pick out any one of them.

Start herelengthat` `Must know

A string is text: a row of characters, each with a position that starts at 0. You can wrap it in single quotes, double quotes or backticks. Backticks are the handy one, because they let you drop values straight into the text with ${ }.

Picture it: positions

Ashaname.at(-1)aPositions start at 0. Negative numbers count from the end.
length

Counts the characters. It is a property, so no brackets.

See the example
Gives a numberOnly reads
str[i]

Reads the character at position i.

See the example
Gives a character or undefinedOnly reads
at(i)

Like str[i], but negative numbers count from the end.

See the example
Gives a character or undefinedOnly reads
charAt(i)

The older way to read one character.

See the example
Gives a character or ""Only reads
`text ${value}`

A template literal: fills values into the text for you.

See the example
Gives a new stringMakes a new one
make.jsJAVASCRIPT
const single = 'Hello';
const double = "Namaste";
const name = "Asha";
const greeting = `Hi ${name}, you have ${2 + 3} messages`; // backticks fill in values

console.log(greeting);
console.log(name.length);          // how many characters
console.log(name[0], name.at(-1)); // first, and last counting from the end
console.log(name.charAt(10));      // out of range gives an empty string

Easy way to remember: use backticks whenever the text has a value inside it. It is easier to read than joining pieces with +.

Terminal OUTPUT
$ node make.js
Hi Asha, you have 5 messages
4
A a
immutable.jsJAVASCRIPT
let word = "cat";
word[0] = "b";                  // ignored: a string cannot be edited in place
console.log(word);

const upper = word.toUpperCase(); // every method gives you a NEW string
console.log(word, upper);

word = "b" + word.slice(1);     // to "change" it, build a new one and reassign
console.log(word);

Why it matters: strings never change. Every tool in this guide gives you a new string, so remember to keep the result.

Terminal OUTPUT
$ node immutable.js
cat
cat CAT
bat
02

Search inside

Check whether some text appears, and find exactly where it is.

SearchingincludesstartsWithindexOf
includes(text)

Checks if the text appears anywhere inside.

See the example
Gives true or falseOnly reads
startsWith(text)

Checks the very beginning.

See the example
Gives true or falseOnly reads
endsWith(text)

Checks the very end.

See the example
Gives true or falseOnly reads
indexOf(text)

Finds where the text first appears.

See the example
Gives a number or -1Only reads
lastIndexOf(text)

Finds where the text last appears.

See the example
Gives a number or -1Only reads
search.jsJAVASCRIPT
const email = "asha.k@razornext.com";

console.log(email.includes("@"));            // is it anywhere inside?
console.log(email.startsWith("asha"));       // at the very start?
console.log(email.endsWith(".com"));         // at the very end?
console.log(email.indexOf("."));             // position of the first match
console.log(email.lastIndexOf("."));         // position of the last match
console.log(email.indexOf("#"));             // -1 means not found
console.log(email.toLowerCase().includes("RAZOR".toLowerCase())); // ignore case

Watch for this: every search is case sensitive. Lower case both sides first when capitals should not matter.

Terminal OUTPUT
$ node search.js
true
true
true
4
16
-1
true
03

Cut and join

Take a piece of a string, split it into an array, and glue arrays back into text.

Cuttingslicesplitjoin

Picture it: split

"report-2026-09.pdf"split("-")"report""2026""09.pdf"The string becomes an array, cut at every dash.
slice(start, end)

Copies the part from start up to, but not including, end. Negatives count from the end.

See the example
Gives a new stringMakes a copy
substring(start, end)

Like slice, but treats negatives as 0. Prefer slice.

See the example
Gives a new stringMakes a copy
split(separator)

Cuts the string at every separator.

See the example
Gives an array of stringsMakes a copy
array.join(glue)

The opposite of split: glues array items into one string.

See the example
Gives a new stringMakes a copy
cut.jsJAVASCRIPT
const file = "report-2026-09.pdf";

console.log(file.slice(0, 6));      // from 0 up to, not including, 6
console.log(file.slice(-3));        // the last 3 characters
console.log(file.slice(7, -4));     // negative numbers count from the end

const parts = file.split("-");      // cut into an array at every "-"
console.log(parts);
console.log(parts.join(" / "));     // glue an array back into one string

console.log("a,b,,c".split(","));   // empty pieces are kept
console.log([..."abc"]);            // split into single characters

Easy way to remember: split turns text into an array so you can use array tools, and join turns it back.

Terminal OUTPUT
$ node cut.js
report
pdf
2026-09
[ 'report', '2026', '09.pdf' ]
report / 2026 / 09.pdf
[ 'a', 'b', '', 'c' ]
[ 'a', 'b', 'c' ]
04

Tidy and shape

Change the case, strip stray spaces and pad text to a fixed width.

FormattingtrimtoUpperCasepadStart
trim()

Removes spaces, tabs and line breaks at both ends.

See the example
Gives a new stringMakes a copy
trimStart / trimEnd()

Removes them at just one end.

See the example
Gives a new stringMakes a copy
toUpperCase()

Makes every letter a capital.

See the example
Gives a new stringMakes a copy
toLowerCase()

Makes every letter small.

See the example
Gives a new stringMakes a copy
padStart / padEnd(length, fill)

Adds fill characters until the string is that long.

See the example
Gives a new stringMakes a copy
repeat(times)

Copies the string that many times in a row.

See the example
Gives a new stringMakes a copy
look.jsJAVASCRIPT
const raw = "   Shree Kumar   ";

console.log(`[${raw.trim()}]`);        // remove spaces at both ends
console.log(`[${raw.trimStart()}]`);   // only at the start
console.log(raw.trim().toUpperCase());
console.log(raw.trim().toLowerCase());

console.log("7".padStart(3, "0"));     // "007": fill on the left
console.log("Total".padEnd(10, ".") + "₹450");
console.log("ab".repeat(3));

Rule of thumb: trim anything a person typed before you save or compare it. Stray spaces cause more bugs than you would think.

Terminal OUTPUT
$ node look.js
[Shree Kumar]
[Shree Kumar   ]
SHREE KUMAR
shree kumar
007
Total.....₹450
ababab
05

Replace parts

Swap one piece of text for another, once or everywhere.

ReplacingreplacereplaceAllregex

Picture it: replaceAll

red apple, red carreplaceAll("red", "blue")blue apple, blue carEvery match is swapped, not just the first.
replace(find, with)

Swaps only the first match.

See the example
Gives a new stringMakes a copy
replaceAll(find, with)

Swaps every match.

See the example
Gives a new stringMakes a copy
replace(/x/g, ...)

A regular expression with g matches patterns, like every digit.

See the example
Gives a new stringMakes a copy
replace(find, fn)

Your helper decides what each match becomes.

See the example
Gives a new stringMakes a copy
replace.jsJAVASCRIPT
const text = "red apple, red car, red door";

console.log(text.replace("red", "blue"));     // only the first match
console.log(text.replaceAll("red", "blue"));  // every match
console.log(text.replace(/red/g, "green"));   // a regex with g also means every match

// the replacement can be a function of what was found
const phone = "call 98765 43210 now";
console.log(phone.replace(/\d/g, (digit, index) => (index < 11 ? "*" : digit)));

Watch for this: replace with plain text only changes the first match. Reach for replaceAll when you mean all of them.

Terminal OUTPUT
$ node replace.js
blue apple, red car, red door
blue apple, blue car, blue door
green apple, green car, green door
call ***** 43210 now
06

Compare and sort

Check if two strings match and put words in the order a person expects.

Comparing===localeCompare
QuestionUseNotes
Exactly the same?a === bcase and accents count
Same, ignoring case?a.toLowerCase() === b.toLowerCase()simple and fast
Same, ignoring case and accents?localeCompare(b, undefined, { sensitivity: "base" })gives 0 when they match
Sort words nicelylist.sort((a, b) => a.localeCompare(b))follows language rules
compare.jsJAVASCRIPT
console.log("apple" === "apple");       // exact match
console.log("Apple" === "apple");       // case matters
console.log("b" > "a", "B" > "a");      // compares character codes, capitals come first

const names = ["zoya", "Aman", "émile", "Bina"];
console.log([...names].sort());         // plain sort: capitals, then small, then accents
console.log([...names].sort((a, b) => a.localeCompare(b))); // how a person would sort

const same = (a, b) => a.localeCompare(b, undefined, { sensitivity: "base" }) === 0;
console.log(same("Resume", "résumé"));  // ignores case and accents

Why it matters: plain sort() puts all capitals before small letters and accents last. localeCompare sorts the way a dictionary does.

Terminal OUTPUT
$ node compare.js
true
false
true false
[ 'Aman', 'Bina', 'zoya', 'émile' ]
[ 'Aman', 'Bina', 'émile', 'zoya' ]
true
07

Emoji and characters

Count real characters safely when text has emoji, and work with the numbers behind letters.

Unicode[...str]codePointAt
[...str]

Splits into real characters, keeping emoji whole.

See the example
Gives an arrayMakes a copy
codePointAt(i)

Gives the number behind the character at i.

See the example
Gives a numberOnly reads
String.fromCodePoint(...codes)

Builds a string from those numbers.

See the example
Gives a new stringMakes a new one
chars.jsJAVASCRIPT
const word = "hi👋";

console.log(word.length);          // 4, because the emoji takes two slots
console.log([...word].length);     // 3: spread counts real characters
console.log([...word].reverse().join("")); // safe reverse

console.log("A".codePointAt(0));   // the number behind a character
console.log(String.fromCodePoint(65, 66, 128578));

const multi = `line one
line two`;                         // backticks keep line breaks
console.log(multi.split("\n").length);

Watch for this: length counts storage slots, not characters. Many emoji take two, so use [...str].length when you show a character count to people.

Terminal OUTPUT
$ node chars.js
4
3
👋ih
65
AB🙂
2
08

All together

Clean up a sign up form: fix the name, tidy the email, make a handle and hide the phone number.

Putting it togethertrimsplitslicepadStart

Real forms are messy. People type extra spaces, random capitals and full numbers you should not show back. Each helper below is one line, built from tools in the earlier modules.

profile.jsJAVASCRIPT
// clean up what a person typed into a sign up form
const form = { name: "  sHREE kumar sharma ", email: " Shree.S@Mail.com ", phone: "9876543210" };

// 1. title case: trim, split into words, capitalise the first letter of each
const titleCase = (s) =>
  s.trim().toLowerCase().split(/\s+/).map((w) => w[0].toUpperCase() + w.slice(1)).join(" ");

// 2. a short handle from the name
const handle = (s) => "@" + titleCase(s).split(" ").map((w) => w.slice(0, 3)).join("").toLowerCase();

// 3. hide most of the phone number
const mask = (p) => p.slice(-4).padStart(p.length, "•");

const clean = {
  name: titleCase(form.name),
  email: form.email.trim().toLowerCase(),
  handle: handle(form.name),
  phone: mask(form.phone),
};
console.log(clean.handle, clean.phone);
console.log(`${clean.name} <${clean.email}> joined as ${clean.handle}`);

What each part uses: trim and case from module 04, split and join from 03, slice from 03 again, and padStart from 04 to mask the phone.

Terminal OUTPUT
$ node profile.js
@shrkumsha ••••••3210
Shree Kumar Sharma <shree.s@mail.com> joined as @shrkumsha
TerminalBASH
# save any example as a file and run it with Node 22
$ node profile.js
# or paste it into your browser console with F12

Which one do I need?

Start from what you want to do, then read across to the tool and what it gives back.

I want toUseYou get
Count charactersstr.lengtha number
Read the last characterstr.at(-1)one character
Check it contains textstr.includes(x)true or false
Find where text isstr.indexOf(x)a position or -1
Take a piecestr.slice(a, b)a new string
Cut into an arraystr.split(",")an array
Remove outer spacesstr.trim()a new string
Change casetoUpperCase / toLowerCasea new string
Add leading zerosstr.padStart(3, "0")a new string
Swap every matchstr.replaceAll(a, b)a new string
Sort words nicelya.localeCompare(b)a negative, 0 or positive number
Count emoji safely[...str].lengtha number
Fill in values`Hi ${name}`a new string