Skip to main content

Strings

Strings are sequences of characters used for text representation. They behave exactly like JavaScript strings, supporting both single-line and multi-line text, as well as format strings.

Declaring Strings

Strings can be created using either single (') or double (") quotes.

const str1 = "Hello, world!";
const str2 = 'Single-quoted string';

String Escaping

Escape sequences allow special characters within strings:

const str3 = "Line 1\nLine 2";  // Newline
const str4 = "Tab\tIndent"; // Tab
const str5 = "Quote: \"Text\""; // Escaped quotes

Template Literals (Format Strings)

Format strings allow embedding expressions inside backticks (`):

const name = "Alice";
const greeting = `Hello, ${name}!`;
console.log(greeting); // "Hello, Alice!"

Multi-line Strings

Backticks also allow multi-line strings without explicit escape sequences:

const multiLine = `This is a
multi-line string.`;

Concatenation

const fullName = "Alice" + " " + "Smith";

Length Property

Returns the number of characters in the string.

const text = "Hello";
console.log(text.length); // 5u

⚠️ The length property returns an unsigned integer!

Accessing Characters

const char = text[1]; // 'e'

Iteration

You can iterate over a string using a for loop

for(let i = 0; i < text.length; i++)
console.log(text[i]);

Or alternatively by using a ranged for loop

for(const elem : text)
console.log(elem);

⚠️ elem is a copy, so modifying it within the loop does not affect the original string