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.

Related String Methods:toLowerCase() toUpperCase() startsWith() includes() replaceAll endsWith() indexOf() replace() slice() split() trim()

1. Creating Strings

JavaScript provides three ways to create strings: single quotes, double quotes, and backticks.

HTML
<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.

💡 Tip: In team projects, stick with one quote style (single or double) throughout the codebase for consistency.


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.

HTML
<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 Yourself

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.


4. Template Literals

Strings created with backticks (`) are called template literals. They have two killer features:

  1. Multiline support — no need for \n; just press Enter
  2. Interpolation — embed variables or expressions with ${variable}
HTML
<!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 Yourself
💡 Tip: When you have many variables, template literals are ten times more readable than concatenation. Don't hesitate — prefer backticks in your daily code.


5. 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 Yourself
⚠️ Note: The backslash itself must be escaped. When writing Windows paths like C:\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:

HTML
<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 Yourself

Using template literals inside loops to generate HTML is extremely common in real-world development and far more pleasant than concatenation.


Related String Methods:toLowerCase() toUpperCase() startsWith() includes() replaceAll endsWith() indexOf() replace() slice() split() trim()

❓ FAQ

Q What's the difference between indexOf and includes?
A 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.
Q Why does replace only replace the first match?
A 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').
Q Which should I use — single quotes or double quotes?
A They're functionally identical. Just be consistent within your team. Most projects use single quotes by default and switch to double quotes when the string itself contains single quotes.

📖 Summary

📝 Exercises

  1. Write a program that takes a sentence as input and outputs the word count (hint: use split by spaces, then length).
  2. Write a program that transforms the string " Hello World " into the fully lowercased, trimmed "hello world" using trim and toLowerCase.
  3. 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.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏