A string stores text. JavaScript strings can use single quotes, double quotes, or backticks. Backticks create a template string, where ${expression} inserts a value.
const name = "Mina";
const message = `Hello, ${name}!`;
console.log(message);Length and characters
The length property gives the character count. Square brackets read a character by its zero-based index; an out-of-range index produces undefined.
const text = "JavaScript";
console.log(text.length); // 10
console.log(text[0]); // J
console.log(text[text.length - 1]); // tStrings are immutable: you cannot change a character inside an existing string. Concatenation and string methods produce a new string instead.
Slicing, finding, and replacing
slice(start, end) extracts text from start up to, but not including, end. indexOf(value) returns the first matching position, or -1 when no match exists. replace(oldValue, newValue) returns a new string with a replacement.
const text = "learn JavaScript";
console.log(text.slice(6, 16)); // JavaScript
console.log(text.indexOf("Java")); // 6
console.log(text.replace("learn", "use"));JavaScript string method workshop
Choose a method to inspect its call, return value, and whether the original string changes.
text.length;Returns the character count; the space counts too.
Comparing strings and letter case
Use === to compare string contents. Comparisons are case-sensitive, so call toLowerCase() or toUpperCase() first when letter case should not matter.
const answer = "YES";
if (answer.toLowerCase() === "yes") {
console.log("accepted");
}KNOWLEDGE QUIZ
KNOWLEDGE QUIZ
KNOWLEDGE QUIZ
Build a username
Read a one-word first and last name, build the String username “first.last”, and print it together with its length.
- Read first and last separately with prompt().
- Concatenate first + "." + last.
- Print the username and username.length.
Extract an email domain
Read an email-shaped string and extract the domain after @, reporting an error when @ is absent or the domain is empty.
- Use indexOf to locate @.
- Check for -1 and ensure characters follow @.
- Use substring(position + 1) and print the domain.
Perform one text replacement
Read source text, a search fragment, and a replacement, then replace only the first occurrence.
- Use indexOf to obtain the first match position.
- When absent, keep the source unchanged and report it.
- When found, combine the text before and after the match with substring and print the result.