目录

Strings

A string is a basic type that represents text data. ArkTS provides a rich set of string operation methods and supports features such as template strings and Unicode handling.

String Literals

A string literal is the basic way to represent text data. ArkTS supports three forms of string literals: single quotes, double quotes, and template strings. They are used to represent text content (such as user input, messages, and configuration values), define identifiers and names (such as file paths and API endpoints), construct output information (such as logs and error messages), and store and pass text data.

[h2]String Declaration

A string can be declared with single quotes, double quotes, or backticks. Single quotes are recommended for style consistency.

let single: string = 'Hello';
let double: string = "World";
let template: string = `ArkTS`;

Single quotes are the most common form. Double quotes are functionally identical to single quotes and differ only in style. They are mainly used for JSON data or strings containing single quotes. Template strings (backticks) support more features such as interpolation and multiline text.

[h2]Special Characters in String Literals

Special characters must be represented using escape characters, including the newline character \n, the tab character \t, quotation marks, and so on.

let newline: string = 'Line1\nLine2';
let tab: string = 'Column1\tColumn2';
let quote: string = 'It\'s a test';
let backslash: string = 'Path: C:\\Users';
let mixed: string = 'Hello\n\tWorld';

[h2]Template Strings

Template literals (backticks) are the most versatile form of string literal. They preserve formatting (line breaks and spaces) and support variable and expression interpolation with ${}. They are suitable for long text (such as email content and HTML fragments), code snippets (such as SQL queries), formatted reports and documents, and dynamic text (such as logs and error messages).

Template literals support multiline text without escape characters:

let multiLine: string = `Line 1
Line 2
Line 3`;

let paragraph: string = `This is a paragraph
that spans multiple lines
of text`;

Line breaks, indentation, and spaces within backticks are all preserved, so the format matches the displayed result, which facilitates reading and maintenance.

Template literals use ${} to interpolate variables and expressions. Expression results are automatically converted to strings:

let name: string = 'Alice';
let age: number = 25;

// Variable interpolation
let interpMessage: string = `Hello, ${name}`;
console.info(`${interpMessage}`);  // 'Hello, Alice'

// Expression interpolation
let info: string = `Name: ${name}, Age: ${age}`;
let nextAge: string = `Next year: ${age + 1}`;

// Object property interpolation
interface User {
  name: string;
  email: string;
}

let user: User = { name: 'Bob', email: 'bob@example.com' };
let profile: string = `User: ${user.name} (${user.email})`;

Interpolation must contain a valid expression, not a complex statement:

// Supported expression types
let a: number = 10;
let b: number = 20;

let arithmetic: string = `${a + b}`;         // '30'
let comparison: string = `${a > b}`;         // 'false'
let logical: string = `${a > 0 && b > 0}`;   // 'true'
let functionCall: string = `${Math.max(a, b)}`; // '20'

// Supports the ternary operator
let result: string = `${a > b ? 'greater' : 'less'}`;  // 'less'

// Does not support complex statements
let invalid: string = `${if (a > b) { 'yes' }}`;  // Compilation error: ${} accepts only expressions; if is a statement, not an expression.

// Nested template string.
let outer: string = `Outer: ${`Inner: ${a}`}`;  // 'Outer: Inner: 10'

In a template literal, ${} triggers interpolation. To output the literal ${, precede it with a backslash as \${. Escape backticks to avoid ending the string prematurely:

// Template strings preserve line breaks and spaces.
let code: string = `
function hello() {
  console.info('Hello');
}
`;

// Escape backticks and ${.
let escaped: string = `Price: \${100}`;
let backtick: string = `Use \`backticks\``;

String Immutability

A string cannot be modified after it is created. All operations return a new string, which is a core characteristic of strings.

let original: string = 'Hello';

// The method returns a new string.
let modified: string = original.toUpperCase();
console.info(`${original}`);  // 'Hello' (the original string is unchanged)
console.info(`${modified}`);  // 'HELLO'

// The string content cannot be modified directly.
original[0] = 'J';  // Compilation error.

[h2]Declaring Reassignable Bindings with let

Use let to declare a string variable that can be reassigned. This is suitable for scenarios such as dynamically building content, updating state at runtime, processing messages, and receiving user input.

let message: string = 'Hello';
message = 'Hello, World';  // Reassign

let text: string = '';
text += 'Part 1';
text += ' Part 2';

Both reassignment and += concatenation create a new string object; the string object itself is immutable.

[h2]Declaring Non-Reassignable Bindings with const

Use const to declare a non-reassignable string binding, ensuring that the variable always refers to the same string. This applies to immutable information such as configuration constants (for example, the app name and version number), fixed messages, and API endpoints. Uppercase naming (for example, const APP_NAME) is recommended, with centralized definitions and type annotations for easier management.

const APP_NAME: string = 'MyApp';
const VERSION: string = '1.0.0';

APP_NAME = 'NewApp';  // Compilation error: cannot reassign

Common String Operations

Common string operations include concatenation, length, indexing, substrings, comparison, case conversion, searching, replacement, padding, and regular expression matching. Some methods described here were introduced in ES2015 or later ES versions; ArkTS supports all of them.

[h2]String Concatenation

Concatenate strings using the + operator or template strings (...${}...). For multiple variables, template strings (see Template Strings) are clearer than successive + operations:

let firstName: string = 'John';
let lastName: string = 'Doe';

// Use the + operator.
let fullName: string = firstName + ' ' + lastName;  // 'John Doe'

// Use a template literal.
let templateName: string = `${firstName} ${lastName}`;  // 'John Doe'

// Use the concat method.
let combined: string = firstName.concat(' ', lastName);  // 'John Doe'

// Use the join method.
let parts: string[] = [firstName, lastName];
let joined: string = parts.join(' ');  // 'John Doe'

The concatenation assignment operator += appends the right-hand string to the left-hand variable, simplifying concatenation:

let compoundMessage: string = '';

// Use += to concatenate by assignment.
compoundMessage += 'Hello';
compoundMessage += ' ';
compoundMessage += 'World';
console.info(`${compoundMessage}`);  // 'Hello World'

// Use compound assignment.
let compoundText: string = 'Part 1';
compoundText += ' Part 2';  // 'Part 1 Part 2'

[h2]String Length

The length property returns the number of UTF-16 code units in a string, not the number of characters. Most common characters (such as English letters and common Chinese characters) occupy one code unit. Some characters (such as emoji) require two adjacent UTF-16 code units, called a surrogate pair. A string containing surrogate pairs therefore has a length greater than its actual character count.

let lengthText: string = 'Hello';
let length: number = lengthText.length;  // 5

let empty: string = '';
let emptyLength: number = empty.length;  // 0

let space: string = '   ';
let spaceLength: number = space.length;  // 3

// The length of a multiline string includes the newline character.
let lengthMultiLine: string = `Line1
Line2`;
let multiLength: number = lengthMultiLine.length;  // 11 (including \n)

Account for surrogate pairs when calculating the length of strings containing complex Unicode characters:

// Chinese characters: each occupies one code unit, so length equals the character count.
let multibyteChinese: string = 'Hello world';
console.info(`${multibyteChinese.length.toString()}`);  // 4

// Emoji: a surrogate pair encodes one character using two code units.
let multibyteEmoji: string = '';
console.info(`${multibyteEmoji.length.toString()}`);  // 2

// Use for...of to iterate by code point and count characters correctly.
function countCharacters(text: string): number {
  let count: number = 0;
  for (let char of text) {
    count++;
  }
  return count;
}

console.info(`${countCharacters('你好世界').toString()}`);  // 4
console.info(`${countCharacters('').toString()}`);  // 1 (length is 2, but the character count is 1)

[h2]String Indexing

Use an index or charAt to access a character at a specified position, and indexOf/lastIndexOf to locate substrings. charAt and indexed access retrieve a single character, while charCodeAt retrieves a character code. The static type of indexed access is string regardless of the index value. Out-of-bounds indexed access returns undefined at runtime, so check for it before use. Out-of-bounds charAt returns an empty string:

let indexText: string = 'Hello World';

// Access by index.
let first: string = indexText[0];           // 'H'
let fifth: string = indexText[4];           // 'o'
let last: string = indexText[indexText.length - 1];  // 'd'

// charAt method
let second: string = indexText.charAt(1);   // 'e'

// Out-of-bounds access.
let outOfBounds: string = indexText[100];  // undefined at runtime, but the static type is string.
let outOfBounds2: string = indexText.charAt(100);      // '' (empty string)

indexOf locates a substring, while lastIndexOf searches backward:

let searchText: string = 'Hello World';

// Find the character position.
let indexOfO: number = searchText.indexOf('o');      // 4
let indexOfWorld: number = searchText.indexOf('World'); // 6
let lastIndexOfO: number = searchText.lastIndexOf('o'); // 7

// Search from the specified position.
let indexOfO2: number = searchText.indexOf('o', 5);   // 7 (starting from index 5)

// Search for a nonexistent string.
let notFound: number = searchText.indexOf('xyz');    // -1

// Calculate the index offset.
let nextIndex: number = indexOfO + 1;          // 5
let prevIndex: number = indexOfO - 1;          // 3

[h2]Iterating over Characters in a String

ArkTS has no separate character type; a single character is represented by string. Use indexing or a for...of loop to access characters individually.

let iterText: string = 'Hello';

// Use for...of to iterate over characters.
for (let char of iterText) {
  console.info(`${char}`);
}

// Use a for loop to iterate.
for (let i = 0; i < iterText.length; i++) {
  let char: string = iterText[i];
  console.info(`${char}`);
}

// Use split to convert to an array.
let chars: string[] = iterText.split('');
for (let char of chars) {
  console.info(`${char}`);
}

[h2]Representing and Using a Single Character

A character can be represented using a Unicode escape or directly as a single-character string.

let accessText: string = 'Hello';

// Obtain a single character.
let firstChar: string = accessText.charAt(0);   // 'H'
let secondChar: string = accessText.charAt(1);   // 'e'

// Character encoding.
let accessCode: number = accessText.charCodeAt(0);     // 72 (Unicode of 'H')
let codePoint: number = accessText.codePointAt(0) ?? 0; // 72

// Create a character from a code.
let charFromCode: string = String.fromCharCode(72);  // 'H'

[h2]Substrings

Substring operations extract, find, and replace text fragments. Use substring and slice to extract string segments, and split to split a string into an array. Key differences: substring automatically swaps arguments when needed (for example, substring(5, 0) is equivalent to substring(0, 5)) and treats negative arguments as 0. slice does not swap arguments and supports negative indexes counted from the end.

let extractText: string = 'Hello World';

// substring method
let sub1: string = extractText.substring(0, 5);    // 'Hello'
let sub2: string = extractText.substring(6);       // 'World'
let sub3: string = extractText.substring(6, 11);   // 'World'

// slice method
let slice1: string = extractText.slice(0, 5);      // 'Hello'
let slice2: string = extractText.slice(-5);        // 'World' (negative index)
let slice3: string = extractText.slice(6, -1);     // 'Worl'

// substring vs slice
// substring automatically adjusts the parameter order and treats negative numbers as 0; slice does not adjust the parameter order and supports negative indexes.
let subNeg: string = extractText.substring(-2, 3);  // 'Hel' (-2 is treated as 0)
let reversed: string = extractText.substring(5, 0);  // 'Hello' (arguments are swapped)
let reversedSlice: string = extractText.slice(5, 0);  // '' (arguments are not swapped)

A substring is a new string independent of the original. Modifying the substring does not affect the original string:

let original: string = 'Hello World';

// A substring is a new string that exists independently.
let sub: string = original.substring(0, 5);
sub = sub.toUpperCase();  // Modifying the substring does not affect the original string.
console.info(`${original}`);  // 'Hello World'

// Convert the substring to an array.
let substrParts: string[] = sub.split('');
console.info(`[${substrParts.join(', ')}]`);  // '[H, E, L, L, O]'

// Concatenate the substring.
let newString: string = sub + ' ArkTS';  // 'HELLO ArkTS'

// Replace the substring.
let replaced: string = original.replace('Hello', 'Hi');  // 'Hi World'

[h2]String Comparison

String comparison determines equality and sort order and supports locale-sensitive comparison. Use === to compare string values and types, avoiding the implicit conversions of ==.

let str1: string = 'Hello';
let str2: string = 'Hello';
let str3: string = 'World';

// Strict equality comparison.
console.info(`${str1 === str2}`);  // true
console.info(`${str1 === str3}`);  // false
console.info(`${str1 !== str3}`);  // true

// Case-sensitive comparison.
let upper: string = 'HELLO';
console.info(`${str1 === upper}`);  // false (different case)

// Compare ignoring case.
let equalIgnoreCase: boolean =
  str1.toLowerCase() === upper.toLowerCase();  // true

The startsWith method checks whether a string starts with specified text, for example, to validate a format:

let startsWithText: string = 'Hello World';

// startsWith method
let startsWithHello: boolean = startsWithText.startsWith('Hello');  // true
let startsWithWorld: boolean = startsWithText.startsWith('World');  // false

// Check from the specified position.
let startsWithWorld2: boolean = startsWithText.startsWith('World', 6);  // true

// Manual prefix check.
function hasPrefix(text: string, prefix: string): boolean {
  return text.indexOf(prefix) === 0;
}

endsWith() checks whether a string ends with a specified substring:

let endsWithText: string = 'Hello World';

// endsWith method
let endsWithWorld: boolean = endsWithText.endsWith('World');  // true
let endsWithHello: boolean = endsWithText.endsWith('Hello');  // false

// Check the suffix within the specified length.
let endsWithOrld: boolean = endsWithText.endsWith('orld', 11);  // true

// Manually check the suffix.
function hasSuffix(text: string, suffix: string): boolean {
  let startPos: number = text.length - suffix.length;
  return startPos >= 0 && text.indexOf(suffix, startPos) === startPos;
}

[h2]String Case Conversion

Use toUpperCase() and toLowerCase() to convert string case. Indexed string access (such as text[0]) has the type string, on which string methods can be called directly. Out-of-bounds indexes return undefined at runtime.

toUpperCase() converts lowercase letters in a string to uppercase:

let upperText: string = 'hello world';

let upperUpper: string = upperText.toUpperCase();  // 'HELLO WORLD'

// Partially uppercase.
let firstUpper: string = upperText[0].toUpperCase() + upperText.substring(1);  // 'Hello world'

// Capitalize the first letter of each word.
function capitalizeWords(upperText: string): string {
  let words: string[] = upperText.split(' ');
  let capitalized: string[] = words.map((word: string): string => {
    if (word.length === 0) {
      return '';
    }
    return word[0].toUpperCase() + word.substring(1).toLowerCase();
  });
  return capitalized.join(' ');
}

let upperResult: string = capitalizeWords('hello world');  // 'Hello World'

toLowerCase() converts uppercase letters in a string to lowercase:

let lowerText: string = 'Hello World';

let lower: string = lowerText.toLowerCase();  // 'hello world'

// Partially lowercase
let lowerMixed: string = lowerText[0] + lowerText.substring(1).toLowerCase();  // 'Hello world'

// Check whether it is lowercase
function isLowerCase(lowerText: string): boolean {
  return lowerText === lowerText.toLowerCase();
}

console.info(`${isLowerCase('hello')}`);  // true
console.info(`${isLowerCase('Hello')}`);  // false

[h2]Search Methods

Search methods locate substrings or characters in a string. This section summarizes common search methods. For detailed indexOf/lastIndexOf examples, see String Indexing. For startsWith/endsWith examples, see String Comparison.

let searchText2: string = 'Hello World';

// includes: check whether the substring is present.
let hasWorld: boolean = searchText2.includes('World'); // true

[h2]Extraction Methods

Extraction methods obtain substrings within a specified range. For usage and examples of slice/substring/split, see Substrings; they are not repeated here.

[h2]Modification Methods

Modification methods change string content, such as replacing, splitting, and concatenating. This section summarizes common modification methods. For detailed replace examples, see Substrings. For padStart/padEnd/repeat examples, see String Padding and Repetition.

// replaceAll: replace all occurrences.
let multiple: string = 'aa bb aa';
let allReplaced: string = multiple.replaceAll('aa', 'xx');  // 'xx bb xx'

// trim: remove leading and trailing spaces.
let trimmed: string = '  Hello ArkTS  '.trim();  // 'Hello ArkTS'

// trimStart: remove leading spaces.
let trimStart: string = '  Hello ArkTS  '.trimStart();  // 'Hello ArkTS  '

// trimEnd: remove trailing spaces.
let trimEnd: string = '  Hello ArkTS  '.trimEnd();  // '  Hello ArkTS'

[h2]Other Methods

Strings also provide localeCompare to compare two strings. Its return value is only guaranteed to be negative, 0, or positive; the exact value depends on the implementation. Use < 0/=== 0/> 0 for comparisons rather than relying on specific values. All types except null and undefined can be converted to strings using toString (for example, (42).toString()). For null/undefined, check for nullish values first or use ${value} interpolation. toString is also used in topics such as bigint.

// localeCompare: compare two strings using locale rules, returning a negative number, 0, or a positive number.
let comparison: number = 'a'.localeCompare('b');     // A negative number (a < b; the exact value depends on the implementation).
let sameComparison: number = 'a'.localeCompare('a');  // 0 (equal)

[h2]String Padding and Repetition

padStart and padEnd are used to pad a string to a specified length at the beginning or end, and repeat is used to repeat a string.

// padStart: pad at the beginning
let prS1: string = '5'.padStart(3, '0');
console.info(`${prS1}`);  // '005'

let prS2: string = 'hi'.padStart(5, '-');
console.info(`${prS2}`);  // '---hi'

// padEnd: pad at the end
let prS3: string = 'hi'.padEnd(5, '-');
console.info(`${prS3}`);  // 'hi---'

// repeat: repeat the string
let prS4: string = 'ab'.repeat(3);
console.info(`${prS4}`);  // 'ababab'

[h2]Strings and Regular Expressions

Regular expressions match, search, and replace strings. Create them using a /pattern/ literal or a RegExp object. The following example uses literals:

// match: match a regular expression (/quick/ matches the substring 'quick').
let regexText: string = 'The quick brown fox';
let matches: RegExpMatchArray | null = regexText.match(/quick/);

// search: find the match position (/brown/ finds the first occurrence of 'brown').
let regexPos: number = regexText.search(/brown/);  // 10

// replace: replace with a regular expression (/fox/ matches the substring 'fox' to replace).
let regexReplaced: string = regexText.replace(/fox/, 'cat');  // 'The quick brown cat'

// split: split with a regular expression (/\d/ uses a single digit as the delimiter).
let regexParts: string[] = 'a1b2c3d'.split(/\d/);
console.info(`${regexParts}`);  // 'a,b,c,d'

// matchAll: find all matches (/\w+/g globally matches sequences of word characters).
let allMatches: IterableIterator<RegExpMatchArray> = regexText.matchAll(/\w+/g);
for (const match of allMatches) {
  console.info(`${match[0]}`);  // Output in sequence: The, quick, brown, fox
}

Unicode Representation of Strings

Unicode encoding represents international characters and supports multiple encoding forms.

[h2]Unicode Scalar Values

A Unicode scalar value is a valid range of Unicode code points, excluding surrogate code points.

// Unicode character representation
let unicode1: string = 'A';               // Direct character
let unicode2: string = '\u0041';          // Unicode escape ('A')
let unicode3: string = '\x41';            // ASCII escape ('A')

// Unicode code point
let emoji: string = '\u{1F600}';          // '' (emoji)
let chinese: string = '\u{4E2D}';         // the Chinese character for 'middle'

// Obtain the Unicode code point of the character.
let unicodeReprCodePoint: number = 'A'.codePointAt(0) ?? 0;  // 65
let emojiCode: number = ''.codePointAt(0) ?? 0; // 128512

// Create a character from a code point.
let fromCode: string = String.fromCodePoint(65);      // 'A'
let fromEmoji: string = String.fromCodePoint(128512); // ''

[h2]Converting Between Unicode Representations

Use codePointAt and fromCodePoint to convert between strings, Unicode code point arrays, and Unicode escape sequences.

let unicodeText: string = 'Hello';

// Convert the string to an array of Unicode code points.
let codePoints: number[] = [];
for (let char of unicodeText) {
  codePoints.push(char.codePointAt(0) ?? 0);
}
console.info(`${codePoints.join(', ')}`);  // 72, 101, 108, 108, 111

// Convert Unicode code points to a string.
let reconstructed: string = '';
for (let code of codePoints) {
  reconstructed += String.fromCodePoint(code);
}
console.info(`${reconstructed}`);  // 'Hello'

// Unicode escape form
let unicodeEscaped: string = '';
for (let char of unicodeText) {
  let code: number = char.codePointAt(0) ?? 0;
  unicodeEscaped += `\\u${code.toString(16).padStart(4, '0')}`;
}
console.info(`${unicodeEscaped}`);  // '\u0048\u0065\u006c\u006c\u006f'

[h2]Unicode Character Handling

A character in a string may consist of multiple UTF-16 code units (for example, an emoji). Use codePointAt and fromCodePoint to handle complete Unicode code points.

let unicodeEmoji: string = '';
let unicodeCode: number | undefined = unicodeEmoji.codePointAt(0);
if (unicodeCode !== undefined) {
  console.info(`${unicodeCode.toString()}`);  // 127881
}

let unicodeChar: string = String.fromCodePoint(128516);
console.info(`${unicodeChar}`);  // ''

// Iterate by Unicode code points (instead of UTF-16 code units).
let unicodeText2: string = 'ab';
for (let uc of unicodeText2) {
  console.info(`${uc}`);  // Output in sequence: a, , b.
}