JavaScript Strings
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.
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.
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.
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
<!DOCTYPE html>
<html>
<body>
<h2>Common String Methods</h2>
<p id="output"></p>
<script>
let str = ' Hello, JavaScript! ';
let result = '';
result += 'Original: "' + str + '"<br>';
result += 'length: ' + str.length + '<br>';
result += 'trim: "' + str.trim() + '"<br>';
result += 'indexOf("Java"): ' + str.indexOf('Java') + '<br>';
result += 'slice(2,7): "' + str.slice(2, 7) + '"<br>';
result += 'includes("Script"): ' + str.includes('Script') + '<br>';
result += 'startsWith(" H"): ' + str.startsWith(' H') + '<br>';
result += 'toUpperCase: ' + str.toUpperCase() + '<br>';
result += 'replace("JavaScript","World"): ' + str.replace('JavaScript', 'World') + '<br>';
document.getElementById('output').innerHTML = result;
</script>
</body>
</html>
Note 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.
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
<!DOCTYPE html>
<html>
<body>
<h2>Template Literal Comparison</h2>
<p id="output"></p>
<script>
let name = 'Bob';
let city = 'London';
let hobby = 'painting';
let old = 'My name is ' + name + ', I live in ' + city + ', and I enjoy ' + hobby + '.';
let modern = `My name is ${name}, I live in ${city}, and I enjoy ${hobby}.`;
let html = '<strong>Concatenation:</strong>' + old + '<br><br>';
html += '<strong>Template literal:</strong>' + modern + '<br><br>';
let a = 5, b = 3;
html += `<strong>Expressions work too:</strong>${a} + ${b} = ${a + b}<br>`;
html += `<strong>Method calls too:</strong>${name.toUpperCase()}`;
document.getElementById('output').innerHTML = html;
</script>
</body>
</html>
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
<!DOCTYPE html>
<html>
<body>
<h2>Escape Characters Demo</h2>
<p id="output"></p>
<script>
let s1 = 'First line\nSecond line';
let s2 = 'Name\tAge\tCity';
let s3 = 'Path: C:\\Users\\Admin';
let s4 = 'He said: "Hello!"';
let s5 = 'It\'s a nice day';
let html = '';
html += '<strong>\\n newline:</strong><pre>' + s1 + '</pre>';
html += '<strong>\\t tab:</strong><pre>' + s2 + '</pre>';
html += '<strong>\\\\ backslash:</strong>' + s3 + '<br>';
html += '<strong>\\" double quote:</strong>' + s4 + '<br>';
html += "<strong>\\' single quote:</strong>" + s5 + '<br>';
document.getElementById('output').innerHTML = html;
</script>
</body>
</html>
C:\Users, you need C:\\Users — forgetting to escape it is a common source of bugs.
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
<!DOCTYPE html>
<html>
<body>
<h2>Generating Content with Template Literals</h2>
<div id="output"></div>
<script>
let products = [
{ name: 'Laptop', price: 999 },
{ name: 'Mouse', price: 29 },
{ name: 'Keyboard', price: 79 }
];
let html = '<ul>';
for (let p of products) {
html += `<li>${p.name} - $${p.price.toFixed(2)}</li>`;
}
html += '</ul>';
document.getElementById('output').innerHTML = html;
</script>
</body>
</html>
Using template literals inside loops to generate HTML is extremely common in real-world development and far more pleasant than concatenation.
📖 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
❓ 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').📝 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.



