TypeScript Strings
Strings are a basic data type used to represent text data. In TypeScript, the type of strings is string. You can use single quotes ('), double quotes ("), or backticks (`) to create strings.
Creating Strings
let singleQuote: string = 'Hello';
let doubleQuote: string = "World";Template Strings
Template strings are a feature introduced in ES6, using backticks (`). They provide more powerful functionality:
- Embedding expressions: You can embed variables or any valid JavaScript expression in strings using
${expression}syntax. - Multi-line strings: Strings can span multiple lines without needing to use
+or\.
Example
let name: string = "TypeScript";
let version: number = 5.2;
// Embedding variables
let greeting: string = `Hello, ${name}!`;
console.log(greeting); // Output: Hello, TypeScript!
// Embedding expressions
let message: string = `The next version will be ${version + 0.1}.`;
console.log(message); // Output: The next version will be 5.3.
// Multi-line strings
let multiLine: string = `
This is a string
that spans across
multiple lines.
`;
console.log(multiLine);Common String Properties and Methods
TypeScript strings have the same properties and methods as JavaScript strings.
length Property
Returns the length of the string.
let str = "Hello, World!";
console.log(str.length); // 13Common Methods
charAt(index): Returns the character at the specified index position.typescriptconsole.log(str.charAt(0)); // 'H'concat(...strings): Concatenates one or more strings and returns a new string.typescriptlet str1 = "Hello"; let str2 = " World"; console.log(str1.concat(str2, "!")); // "Hello World!"indexOf(searchValue): Returns the index of the first occurrence of the specified substring, or -1 if not found.typescriptconsole.log(str.indexOf('o')); // 4 console.log(str.indexOf('z')); // -1slice(startIndex, endIndex): Extracts a section of a string and returns a new string.endIndexis optional.typescriptconsole.log(str.slice(0, 5)); // "Hello" console.log(str.slice(7)); // "World!"split(separator): Splits a string into an array of strings using the specified separator.typescriptlet words = str.split(' '); console.log(words); // ["Hello,", "World!"]toLowerCase(): Converts the string to lowercase.typescriptconsole.log(str.toLowerCase()); // "hello, world!"toUpperCase(): Converts the string to uppercase.typescriptconsole.log(str.toUpperCase()); // "HELLO, WORLD!"trim(): Removes whitespace from both ends of the string.typescriptlet paddedStr = " some text "; console.log(paddedStr.trim()); // "some text"substring(startIndex, endIndex): Returns the substring between the specified indexes.typescriptconsole.log(str.substring(0, 5)); // "Hello"
Thanks to TypeScript's type system, when you call these methods, IDEs (like VS Code) can provide intelligent auto-completion and parameter information hints, greatly improving development efficiency.