Strings
Strings hold text, written between quotes.
Syntax
let text = 'Hello';
text.lengthA string is a sequence of characters used for text. You can write strings with single quotes, double quotes, or backticks.
Length and concatenation
str.lengthgives the number of characters.- The
+operator joins (concatenates) strings.
Example
Loading editor…
Press Run to execute the code.
When to use it
- Store and display a product description retrieved from a database as a string.
- Combine a user's first and last name into a greeting string for a welcome message.
- Escape special characters in a user-supplied string before inserting it into a URL query.
More examples
Declare and concatenate strings
Uses the + operator to concatenate two strings with a space between them.
const first = "Jane";
const last = "Doe";
const full = first + " " + last;
console.log(full); // "Jane Doe"String length and index access
Accesses the length property and individual characters by zero-based index on a string.
const word = "JavaScript";
console.log(word.length); // 10
console.log(word[0]); // "J"
console.log(word[4]); // "S"Single double and backtick quotes
Shows all three ways to delimit strings in JavaScript, including template literals with interpolation.
const a = 'single-quoted string';
const b = "double-quoted string";
const c = `Template: ${1 + 1} items`;
console.log(a, b, c);
Discussion