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.`;

Hex Literal Strings

Hex literal strings allow you to define string content using hexadecimal byte values. This is useful for embedding binary or encoded data directly.

const hexStr = "\x48\x65\x6C\x6C\x6F\x2C\x20\x77\x6F\x72\x6C\x64\x21";
console.log(hexStr); // "Hello, world!"

Each \xNN represents a single byte, where NN is a (one or two)-digit hexadecimal number.

💡 Hex literals are especially useful for non-printable characters or precise byte-level control.

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