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
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
Common String Properties and Methods
TypeScript strings have the same properties and methods as JavaScript strings.
length Property
Returns the length of the string.
Common Methods
-
charAt(index): Returns the character at the specified index position. -
concat(...strings): Concatenates one or more strings and returns a new string. -
indexOf(searchValue): Returns the index of the first occurrence of the specified substring, or -1 if not found. -
slice(startIndex, endIndex): Extracts a section of a string and returns a new string.endIndexis optional. -
split(separator): Splits a string into an array of strings using the specified separator. -
toLowerCase(): Converts the string to lowercase. -
toUpperCase(): Converts the string to uppercase. -
trim(): Removes whitespace from both ends of the string. -
substring(startIndex, endIndex): Returns the substring between the specified indexes.
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.