8. JavaScript Strings
What you will learn
- How to write strings and use special characters
- String length and indexing
- The most useful string methods
- How to search, extract, and change text
Writing strings
A string is text inside matching quotes. Use whichever quote type avoids clashes with the text itself.
Example
<p id="demo"></p>
<script>
const a = "She said 'hello'";
const b = 'It is "great"';
const c = "It's fine";
document.getElementById("demo").innerHTML = a + "<br>" + b + "<br>" + c;
</script>
Output (after the script runs)
She said ‘hello’
It is “great”
It’s fine
Escape characters
A backslash \ lets you include special characters.
| Code | Result |
|---|---|
\" |
A double quote |
\' |
A single quote |
\\ |
A backslash |
\n |
A new line |
\t |
A tab |
Length and positions
length gives the number of characters. Each character has a position, counting from 0.
Example
<p id="demo"></p>
<script>
const word = "JavaScript";
document.getElementById("demo").innerHTML =
"Length: " + word.length + "<br>" +
"First letter: " + word[0] + "<br>" +
"Last letter: " + word[word.length - 1];
</script>
Output (after the script runs)
Length: 10
First letter: J
Last letter: t
Joining strings
Use + to join strings. The next lessons show template literals, a cleaner way.
Useful methods
Strings cannot be changed in place. A method returns a new string and leaves the original alone.
| Method | What it does |
|---|---|
toUpperCase(), toLowerCase() |
Change case |
trim() |
Remove spaces from both ends |
slice(start, end) |
Extract part of the text |
indexOf(text) |
Position of the first match, or -1 |
includes(text) |
True if the text is found |
startsWith(text), endsWith(text) |
Check the beginning or end |
replace(old, new) |
Replace the first match |
replaceAll(old, new) |
Replace every match |
split(separator) |
Turn a string into an array |
padStart(length, fill) |
Add characters at the start |
repeat(count) |
Repeat the text |
Example
<p id="demo"></p>
<script>
const text = " Learn JavaScript Today ";
const clean = text.trim();
document.getElementById("demo").innerHTML =
"Trimmed: '" + clean + "'<br>" +
"Upper: " + clean.toUpperCase() + "<br>" +
"Lower: " + clean.toLowerCase() + "<br>" +
"Slice(6, 16): " + clean.slice(6, 16) + "<br>" +
"Index of 'Script': " + clean.indexOf("Script") + "<br>" +
"Includes 'Today': " + clean.includes("Today") + "<br>" +
"Replace: " + clean.replace("Today", "Daily");
</script>
Output (after the script runs)
Trimmed: ‘Learn JavaScript Today’
Upper: LEARN JAVASCRIPT TODAY
Lower: learn javascript today
Slice(6, 16): JavaScript
Index of ‘Script’: 10
Includes ‘Today’: true
Replace: Learn JavaScript Daily
slice(start, end) includes the character at start but stops before end. Negative numbers count from the end of the string.
Splitting text
Example
<p id="demo"></p>
<script>
const tags = "html,css,javascript";
const list = tags.split(",");
document.getElementById("demo").textContent =
"Count: " + list.length + ", second item: " + list[1];
</script>
Output (after the script runs)
Count: 3, second item: css
Strings are immutable
Example
<p id="demo"></p>
<script>
let word = "cat";
word.toUpperCase(); // result is thrown away
const first = word; // still "cat"
word = word.toUpperCase(); // store the new string
document.getElementById("demo").textContent = first + " then " + word;
</script>
Output (after the script runs)
cat then CAT
Calling a method alone does nothing useful. You must save its result.
Comparing text
Comparison is case sensitive, so "Apple" === "apple" is false. To compare without caring about case, convert both sides first: a.toLowerCase() === b.toLowerCase().
Common mistakes
- Counting positions from 1. The first character is at position 0.
- Forgetting that methods return a new string.
- Mixing up
sliceend positions, which are not included. - Forgetting that
replace()changes only the first match. - Putting a real new line inside normal quotes. Use
\n.
Exercise
Clean the email address by removing the surrounding spaces and converting it to lower case, then show the cleaned address and whether it contains an @ symbol.
Show solution
<p id="demo"></p>
<script>
const email = " Sam@Example.com ";
const clean = email.trim().toLowerCase();
document.getElementById("demo").textContent =
clean + " has @: " + clean.includes("@");
</script>
Knowledge check
1. What is the position of the first character in a string?
0.
2. Which method removes spaces from both ends?
trim()
3. Can you change a string in place?
No. Strings are immutable, so methods return a new string.
Summary
- Strings are text with positions starting at 0.
- Methods such as
trim,slice,includes, andreplacereturn new strings. - Use
splitto turn text into an array.