Week 3: Talking to Your Program and Mastering Text
Learn how to interact with users and manipulate strings effectively in JavaScript.
Explore Chapter 3String Properties and Basic Manipulation.
Strings are sequences of characters. JavaScript provides ways to access information about strings and perform basic operations.
length Property
The length property returns the number of characters in a string.
let text = "JavaScript";
console.log(text.length); // Output: 10
Accessing Characters (Indexing)
You can access individual characters in a string using bracket notation [] with the character's index (position). Indices start at 0.
let language = "JavaScript";
let firstChar = language[0]; // 'J'
let secondChar = language[1]; // 'a'
let lastChar = language[language.length - 1]; // 't'
console.log("First:", firstChar, "Last:", lastChar);
// Note: Strings are immutable in JS. You cannot change a character like this:
// language[0] = 'j'; // This will not work or cause an error silently.
Trying to access an index outside the string's bounds usually returns undefined.
Concatenation (+) Operator)
The + operator concatenates (joins) strings together.
let str1 = "Hello";
let str2 = "World";
let combined = str1 + " " + str2 + "!"; // "Hello World!"
console.log(combined);
Template Literals (Template Strings).
Introduced in ES6, template literals provide an easier and more readable way to create strings, especially those containing variables or expressions.
They are enclosed by backticks (`` ` ``) instead of single or double quotes.
Features:
- Embedded Expressions: You can embed variables and expressions directly within the string using the ${expression} syntax. The expression is evaluated, and its result is included in the string.
let userName = "Bob"; let items = 3; let total = 75.50; let report = `User: ${userName} Items purchased: ${items} Total cost: $${total.toFixed(2)}`; // .toFixed(2) formats the number console.log(report); /* Output: User: Bob Items purchased: 3 Total cost: $75.50 */ - Multiline Strings: Strings created with backticks can span multiple lines without needing special characters like \n.
let poem = `The rain in Spain falls mainly on the plain.`; console.log(poem);
Template literals are generally preferred over traditional string concatenation (+) for embedding variables due to their improved readability.