Essential String Methods

JavaScript ES2024 · ✓ verified by execution on

Strings in JavaScript come with powerful built-in methods to manipulate text.

String methods do not modify the original string (strings are immutable); they always return a new string.

Changing Case

You can easily change the case of a string.

javascript
const text = "Hello World";
console.log(text.toUpperCase());
console.log(text.toLowerCase());
Output
HELLO WORLD
hello world

Trimming Whitespace

When accepting user input, you often need to clean up extra spaces. trim() removes whitespace from both ends of a string, but leaves internal spaces intact.

javascript
console.log('  hello \n'.trim());
Output
hello

Extracting Substrings

You can extract a specific part of a string using slice().

javascript
const str = "CodeLudo";
console.log(str.slice(0, 4));
Output
Code

A powerful feature of slice() is its support for negative indices, which count backwards from the end of the string.

javascript · visualize
const str = "CodeLudo";
const ending = str.slice(-4);
console.log(ending);
Ludo

substring() is an alternative that behaves similarly but handles arguments differently.

Why Two Similar Methods Exist

You might wonder why JavaScript has both slice() and substring() if they do almost the same thing. The language designers added substring() first in early versions of JavaScript. It is forgiving in a way that turned out to be a mistake: pass a start index greater than the end, say substring(4, 0), and it silently swaps them to 0, 4. Your typo returns a plausible string instead of an obvious wrong answer.

slice() came later and does not swap: start greater than end returns an empty string, which is a visible wrong answer rather than a hidden one. slice() also reads negative indices as counting back from the end, where substring() treats any negative number as 0. Reach for slice() unless you have a reason not to.

Both take the end index as exclusive, which is the source of most off-by-one errors here: 'CodeLudo'.slice(0, 4) gives 'Code', not 'CodeL'. The second number is where to stop, not the last character to keep. Once that clicks, slice(4) with no end — everything from index 4 onward — reads naturally too.

Neither method changes the original. Strings are immutable, so every one of these returns a new string and leaves the old one untouched. text.slice(0, 4) on its own line does nothing at all; you have to assign the result somewhere.

"JavaScript" .substring() .slice() (4, 0) Swaps to (0, 4) → "Java" Fails safely → "" (-6) Treats as 0 → "JavaScript" Counts back → "Script"
Behavior differences between slice() and substring()

What do you think this outputs based on the rules?

Predict the output javascript

Read the code. What exactly will it print? Commit to an answer before you look.

let word = "Java";
let result = word.substring(-6);
console.log(result + "Script");
Output
JavaScript

(Note: Because substring treats -6 as 0, it simply returns the entire string "Java"!)

Searching Strings

Search methods are strictly case-sensitive.

javascript
console.log('JavaScript'.includes('Script'));
console.log('javascript'.startsWith('Java'));
Output
true
false

Check yourself

What does the trim() method remove?

Reveal answer

Whitespace from both ends of a string. — trim() removes whitespace and line terminators exclusively from both ends of the string.

How does slice() handle negative indices?

Reveal answer

It counts backward from the end of the string. — A negative index in slice() is treated as an offset from the end of the string.

Are string search methods like includes() case-sensitive?

Reveal answer

Yes, they are strictly case-sensitive. — Methods like includes(), startsWith(), and endsWith() are always case-sensitive in JavaScript.

Challenges

🐞 Bug Hunt +30 XP

Bug Hunt: The developer is trying to remove the extra whitespace from the user's input, but it's not working. Fix the code so it correctly trims the string.

This code runs. It just does the wrong thing. Read it, find the defect, fix it — the tests below decide when you are right.

javascript
  • Test 1 — expects "CodeLudo"
Need a hint? (−25% XP)

String methods do not modify the original string (strings are immutable); they always return a new string. You must reassign it.

Show solution (0 XP)
let input = '   CodeLudo   ';
input = input.trim();
console.log(input);

Challenge 2 +20 XP

Extract the word 'JavaScript' from the end of the string using a negative index with slice().

javascript
  • Test 1 — expects "JavaScript"
Need a hint? (−25% XP)

'JavaScript' is 10 characters long, so you want to slice starting from 10 characters before the end.

Show solution (0 XP)
const text = 'I love JavaScript';
const extract = text.slice(-10);
console.log(extract);