Strings
Strings are text. Names, messages, emails and URLs are all strings, and JavaScript gives you powerful tools to work with them.
On this page · 5 min · Beginner
On this page
- Learning objectives
- Explanation
- Code example
- Step by step
- Real-world use
- Common mistakes
- Best practices
- Remember this
- Practice exercise
- Mini quiz
- Related topics
- My notes
- Reading time
- 5 min
- Difficulty
- Beginner
- Updated
- Oct 27, 2026
Learning objectives#
- Measure and clean strings
- Search inside strings
- Extract and replace parts of strings
- Split strings into arrays
Explanation#
Strings can use single quotes, double quotes or backticks. Backticks allow ${expressions} inside (template literals).
Strings are immutable: methods like toUpperCase return a new string; the original is unchanged.
Common tools: trim (remove outer spaces), includes/startsWith (search), slice (cut out part), replace (swap text), split (turn into an array).
Code example: Working with text#
const raw = ' Hello, JavaScript! ';
const s = raw.trim();
console.log(s.length);
console.log(s.toUpperCase());
console.log(s.includes('Java'), s.startsWith('Hello'));
console.log(s.slice(7, 17));
console.log(s.replace('JavaScript', 'World'));
console.log('a,b,c'.split(','));
console.log('ab'.repeat(3), '5'.padStart(3, '0'));
18 HELLO, JAVASCRIPT! true true JavaScript Hello, World! [ 'a', 'b', 'c' ] ababab 005
Step-by-step explanation#
- trim removes the spaces at both ends, leaving 18 characters.
- toUpperCase returns a new upper-case string.
- slice(7, 17) copies characters 7 to 16 — the word “JavaScript”.
- split(',') breaks a string into an array at each comma.
- padStart(3, '0') pads to 3 characters: "005" — handy for invoice numbers.
Real-world use case#
Cleaning form input (trim), checking an email domain (endsWith), building slugs for URLs (toLowerCase + replaceAll), and parsing CSV lines (split).
Common mistakes#
name.toUpperCase() returns a new string; name itself is unchanged. Assign the result.
'a-b-c'.replace('-', '') gives 'ab-c'. Use replaceAll for every match.
Best practices#
- Trim user input before validating
- Use includes/startsWith/endsWith instead of indexOf checks
- Use template literals to build strings
- Use toLowerCase() for case-insensitive comparisons
Remember this#
Strings never change — methods hand you a new copy.
slice(start, end): end is NOT included.
split turns text → array; join turns array → text.
Practice exercise#
Your task: Turn the title " Learn JavaScript Fast " into a URL slug: "learn-javascript-fast".
Show solution
const title = ' Learn JavaScript Fast ';
const slug = title.trim().toLowerCase().split(' ').join('-');
console.log(slug); // learn-javascript-fast
Mini quiz#
What is printed?
console.log('banana'.slice(1, 4));
Want more? Practise all JavaScript MCQs · JavaScript interview questions
My notes#
Saved in this browser.