TypeScript String (Strings)
In TypeScript, String is the basic data type used to represent text data. It inherits and extends JavaScript's string features while adding static type checking.
Syntax
var txt = new String("string");
Or a simpler way:
var txt = "string";
Two creation methods and their core differences
There are two ways to create strings in TypeScript, but they differ essentially in type, performance, and use cases:
Method 1: String literal (recommended)
This is the most commonly used and best-performing method in TypeScript/JavaScript; it creates a primitive string type (string), which is also the default string type in TypeScript's type system.
// Raw string (recommended)
const txt1: string = "Hello TypeScript"; // 显式指定类型
const txt2 = "Hello JavaScript"; // 类型推导为 string
Method 2: String object (not recommended)
Creating via new String() produces a wrapper object type (String), which is essentially an object rather than a primitive value, causing type confusion and performance overhead.
// String object (not recommended)
const txtObj: String = new String("Hello Object"); // 类型为 String(对象)
String objects and string literals are different in type:
- A string literal is a primitive data type
string, used to directly store string values. StringThe object is an instance of theStringtype is actually an object, not a primitive string value.
Example
let strLiteral
:
string
=
"Hello"
;
let strObject
:
String
=
new
String
(
"Hello"
)
;
console.
log
(
typeof
strLiteral
)
;
// Output: "string"
console.
log
(
typeof
strObject
)
;
// Output: "object"
| Feature | String literal (string) | String object (String) |
|---|---|---|
| Nature of the type | Primitive value | Reference type (object) |
| Performance | Efficient, with no extra memory overhead | Inefficient, creates object instances |
| Type checking (TypeScript) | Conforms to TS primitive type standards | Type mismatch (e.g., a string variable cannot be assigned a String object) |
| Comparison method | Directly compares values | Compares reference addresses (need valueOf() to get the primitive value) |
Type compatibility between string literals and String objects
In TypeScript, string literal types and String object types are not fully compatible.
For example, a string variable cannot directly use String object methods, and vice versa. Therefore, String objects are usually unnecessary.
Example
let strLiteral
:
string
=
"Test"
;
let strObject
:
String
=
new
String
(
"Test"
)
;
console.
log
(
strLiteral
===
strObject
)
;
// Output: false; same content, different types
console.
log
(
strLiteral
==
strObject
)
;
// Output: true; same content
console.
log
(
strLiteral
===
strObject.
valueOf
(
)
)
;
// Output: true; compared after converting the object to a primitive string
strLiteral is a primitive string type (string), while strObject is a String object type (String). This means their types are different.
The above code converted to JavaScript is:
Example
var
strLiteral
=
"Test"
;
var
strObject
=
new
String
(
"Test"
)
;
console.
log
(
strLiteral
===
strObject
)
;
// Output: false; same content, different types
console.
log
(
strLiteral
==
strObject
)
;
// Output: true; same content
console.
log
(
strLiteral
===
strObject.
valueOf
(
)
)
;
// Output: true; compared after converting the object to a primitive string
String object properties
The following table lists the properties supported by String objects:
| No. | Attribute & Description | Example |
|---|---|---|
| 1. | constructor
A reference to the function that created the object. |
var str = new String( "This is string" ); |
| console.log("str.constructor is:" + str.constructor)
Output result: str.constructor is:function String() { [native code] } |
||
| 2. | length
Returns the length of the string. |
var uname = new String("Hello World")
|
| console.log("Length "+uname.length) // Outputs 11 | ||
| 3. | prototype
Allows you to add properties and methods to an object. |
function employee(id:number,name:string) {
|
this.id = id
this.name = name
} var emp = new employee(123,"admin") employee.prototype.email="admin@runoob.com" // Add property email console.log("Employee ID: "+emp.id) console.log("Employee name: "+emp.name) console.log("Employee email: "+emp.email) |
String Methods
The following table lists the methods supported by String objects:
| No. | Method & Description | Example |
|---|---|---|
| 1. | charAt()
Returns the character at the specified position. |
var str = new String("RUNOOB"); console.log("str.charAt(0) is:" + str.charAt(0)); // R console.log("str.charAt(1) is:" + str.charAt(1)); // U console.log("str.charAt(2) is:" + str.charAt(2)); // N console.log("str.charAt(3) is:" + str.charAt(3)); // O console.log("str.charAt(4) is:" + str.charAt(4)); // O console.log("str.charAt(5) is:" + str.charAt(5)); // B | | 2. | charCodeAt()
Returns the Unicode encoding of the character at the specified position.
|var str = new String("RUNOOB");
console.log("str.charCodeAt(0) 为:" + str.charCodeAt(0)); // 82
console.log("str.charCodeAt(1) 为:" + str.charCodeAt(1)); // 85
console.log("str.charCodeAt(2) 为:" + str.charCodeAt(2)); // 78
console.log("str.charCodeAt(3) 为:" + str.charCodeAt(3)); // 79
console.log("str.charCodeAt(4) 为:" + str.charCodeAt(4)); // 79
console.log("str.charCodeAt(5) 为:" + str.charCodeAt(5)); // 66
| | 3. | concat()
Concatenates two or more strings and returns the new string.
|var str1 = new String( "RUNOOB" );
var str2 = new String( "GOOGLE" );
var str3 = str1.concat( str2 );
console.log("str1 + str2 : "+str3) // RUNOOBGOOGLE
| | 4. | indexOf()
Returns the position of the first occurrence of a specified string value in a string.
|var str1 = new String( "RUNOOB" );| | 5. | lastIndexOf()var index = str1.indexOf( "OO" ); console.log("查找的字符串位置 :" + index ); // 3
Searches the string from back to front and returns the last occurrence of the string, counted from the starting position (0).
|var str1 = new String( "This is string one and again string" );
var index = str1.lastIndexOf( "string" );
console.log("lastIndexOf 查找到的最后字符串位置 :" + index ); // 29
index = str1.lastIndexOf( "one" );
console.log("lastIndexOf 查找到的最后字符串位置 :" + index ); // 15
| | 6. | localeCompare()
Compares two strings using a locale-specific order.
|var str1 = new String( "This is beautiful string" );| | 7. |var index = str1.localeCompare( "This is beautiful string");
console.log("localeCompare first :" + index ); // 0
match()
Finds one or more matches of a regular expression.
|var str="The rain in SPAIN stays mainly in the plain"; var n=str.match(/ain/g); // ain,ain,ain| | 8. | replace()
Replaces substrings that match a regular expression
|var re = /(\w+)\s(\w+)/; var str = "zara ali"; var newstr = str.replace(re, "$2, $1"); console.log(newstr); // ali, zara| | 9. | search()
Searches for values that match a regular expression
|var re = /apples/gi;
var str = "Apples are round, and apples are juicy.";
if (str.search(re) == -1 ) {
console.log("Does not contain Apples" );
} else {
console.log("Contains Apples" );
}
| | 10. | slice()
Extracts a portion of a string and returns the extracted part in a new string.
| | 11. | split()Splits a string into an array of substrings.
|var str = "Apples are round, and apples are juicy.";
var splitted = str.split(" ", 3);
console.log(splitted) // [ 'Apples', 'are', 'round,' ]
| | 12. | substr()
Extracts a specified number of characters from a string, starting at a given index.
| | 13. | substring()Extracts the characters between two specified indices in a string.
|var str = "RUNOOB GOOGLE TAOBAO FACEBOOK";
console.log("(1,2): " + str.substring(1,2)); // U
console.log("(0,10): " + str.substring(0, 10)); // RUNOOB GOO
console.log("(5): " + str.substring(5)); // B GOOGLE TAOBAO FACEBOOK
| | 14. | toLocaleLowerCase()
Converts a string to lowercase according to the host's locale; only a few languages (such as Turkish) have locale-specific case mappings.
|var str = "Runoob Google"; console.log(str.toLocaleLowerCase( )); // runoob google| | 15. | toLocaleUpperCase()
Converts a string to uppercase according to the host's locale; only a few languages (such as Turkish) have locale-specific case mappings.
|var str = "Runoob Google"; console.log(str.toLocaleUpperCase( )); // RUNOOB GOOGLE| | 16. | toLowerCase()
Converts a string to lowercase.
|var str = "Runoob Google"; console.log(str.toLowerCase( )); // runoob google| | 17. | toString()
Returns a string.
|var str = "Runoob"; console.log(str.toString( )); // Runoob| | 18. | toUpperCase()
Converts a string to uppercase.
|var str = "Runoob Google"; console.log(str.toUpperCase( )); // RUNOOB GOOGLE| | 19. | valueOf()
Returns the primitive value of the specified String object.
|var str = new String("Runoob");
console.log(str.valueOf( )); // Runoob
|
Recommendations for using String objects
In TypeScript, using String objects is usually unnecessary; using string literals directly is more efficient and aligns with TypeScript best practices:
- Performance:
StringAn object is a reference type that occupies more memory, and creating a new object each time has greater performance overhead. - Type Safety: TypeScript encourages the use of
stringliteral types to keep code concise and consistent.
If you really need to use String object methods, you can use the valueOf() method to convert the object to a primitive string and then continue processing.
In general, TypeScript recommends using string literal types directly to simplify code, improve performance, and avoid unnecessary type conversions and complexity.
Example
let strLiteral
:
string
=
"Use string literals whenever possible!"
;
let strObject
:
String
=
new
String
(
"Avoid using String objects."
)
;
console.
log
(
strLiteral
)
;
// Output: "Use string literals whenever possible!"
console.
log
(
strObject.
valueOf
(
)
)
;
// Output: "Avoid using String objects."