JavaScript: JavaScript Strings
Last updated: 2026-10-13
Strings are one of the most commonly used data types in JavaScript. Nine out of ten lines of code you write involve strings — displaying text, building messages, processing user input — none of it works without them.
1. Creating Strings
JavaScript provides three ways to create strings: single quotes, double quotes, and backticks.
<script>
let a = 'hello'; // Single quotes
let b = "world"; // Double quotes
let c = `hello`; // Backticks
</script>
Single quotes and double quotes are functionally identical — pick whichever you prefer. Backticks, however, are different: they support template literals, which are much more powerful. More on that below.
2. Strings Are Immutable
This is a pitfall many developers hit: once a string is created, its contents cannot be changed. Every method you call returns a new string without modifying the original.
<script>
let str = 'hello';
str[0] = 'H'; // Silently fails — str is still 'hello'
str.toUpperCase(); // Returns 'HELLO', but str itself is unchanged
let upper = str.toUpperCase(); // Correct — capture the return value in a variable
</script>
Remember: string methods never modify the original. You must assign the return value to a new variable.
3. Common Methods
JavaScript has many string methods, but these are the ones you'll use daily:
| Method | Purpose | Example |
|---|---|---|
length |
Get length | 'abc'.length → 3 |
indexOf() |
Find substring position | 'hello'.indexOf('ll') → 2 |
slice() |
Extract substring | 'hello'.slice(1,3) → 'el' |
replace() |
Replace content | 'cat'.replace('c','b') → 'bat' |
toUpperCase() |
Convert to uppercase | 'hi'.toUpperCase() → 'HI' |
toLowerCase() |
Convert to lowercase | 'HI'.toLowerCase() → 'hi' |
trim() |
Remove leading/trailing spaces | ' hi '.trim() → 'hi' |
split() |
Split into array by delimiter | 'a,b'.split(',') → ['a','b'] |
includes() |
Check if substring exists | 'hello'.includes('ell') → true |
startsWith() |
Check if string starts with | 'hello'.startsWith('he') → true |
endsWith() |
Check if string ends with | 'hello'.endsWith('lo') → true |
▶ Example: Common String Methods
▶ Try it YourselfNote that slice(start, end) extracts from start up to but not including end. This is consistent with most languages — you'll get used to it.
4. Template Literals
Strings created with backticks (`) are called template literals. They have two killer features:
- Multiline support — no need for
\n; just press Enter - Interpolation — embed variables or expressions with
${variable}
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Template Literals</title></head>
<body>
<div id="output"></div>
<script>
let name = 'Alice';
let age = 20;
// Old way: concatenation, easy to miss a plus sign
let msg1 = 'My name is ' + name + ', I am ' + age + ' years old.';
// New way: template literals, much cleaner
let msg2 = `My name is ${name}, I am ${age} years old.`;
document.getElementById('output').innerHTML =
'<strong>Concatenation:</strong>' + msg1 + '<br>' +
'<strong>Template literal:</strong>' + msg2;
</script>
</body>
</html>
▶ Example: Template Literals vs Concatenation
▶ Try it Yourself5. Escape Characters
Some characters have special meaning inside strings. To output them literally, use a backslash \ to escape:
| Escape Character | Meaning |
|---|---|
\n |
Newline |
\t |
Tab |
\\ |
Backslash itself |
\" |
Double quote |
\' |
Single quote |
▶ Example: Escape Characters
▶ Try it YourselfC:\Users, you need C:\\Users — forgetting to escape it is a common source of bugs.
6. String Concatenation vs Template Literals
Both approaches work for simple cases, but concatenation quickly becomes painful as the number of variables grows:
<script>
// Concatenation: easy to miss or double up on plus signs
let html = '<div class="' + cls + '">' + title + '</div>';
// Template literal: clear at a glance
let html = `<div class="${cls}">${title}</div>`;
</script>
▶ Example: Generating HTML Content
▶ Try it YourselfUsing template literals inside loops to generate HTML is extremely common in real-world development and far more pleasant than concatenation.
❓ FAQ
indexOf and includes?indexOf returns the starting position of the substring (or -1 if not found), while includes returns a boolean. If you only care whether a substring exists, includes is more intuitive; if you need the exact position, use indexOf.replace only replace the first match?replace only replaces the first match by default. To replace all occurrences, use replaceAll, or use a regex with the g flag: str.replace(/abc/g, 'xyz').📖 Summary
- Strings can be created with single quotes, double quotes, or backticks — prefer backticks
- Strings are immutable; all methods return new strings without modifying the original
slice(start, end)includes start but excludes end;indexOfreturns-1if not found- Template literals use
${}for interpolation and support expressions and method calls - Escape characters start with
\—\nfor newline,\\for a literal backslash trim()is especially useful for processing user input — don't forget to use it
📝 Exercises
- Write a program that takes a sentence as input and outputs the word count (hint: use
splitby spaces, thenlength). - Write a program that transforms the string
" Hello World "into the fully lowercased, trimmed"hello world"usingtrimandtoLowerCase. - Use a template literal to generate a self-introduction HTML snippet containing your name, age, and hobbies (using variables), and display it on the page.