404 Not Found

404 Not Found


nginx

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.

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.

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

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.

Common Methods

JavaScript has many string methods, but these are the ones you'll use daily:

Method Purpose Example
length Get length 'abc'.length3
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

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

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

HTML
<!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>
▶ Try it Yourself
💡 When you have many variables, template literals are ten times more readable than concatenation. Don't hesitate — prefer backticks in your daily code.

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

HTML
<!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>
▶ Try it Yourself
⚠️ 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.

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

HTML
<!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>
▶ Try it Yourself

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


📖 Summary

  1. Strings can be created with single quotes, double quotes, or backticks — prefer backticks
  2. Strings are immutable; all methods return new strings without modifying the original
  3. slice(start, end) includes start but excludes end; indexOf returns -1 if not found
  4. Template literals use ${} for interpolation and support expressions and method calls
  5. Escape characters start with \\n for newline, \\ for a literal backslash
  6. trim() is especially useful for processing user input — don't forget to use it

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

📝 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.
100%

🙏 帮我们做得更好

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

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