TypeScript String

In TypeScript, String is a 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 have essential differences in type, performance, and usage scenarios:

Method 1: String literals (recommended)

This is the most common and performant way in TypeScript/JavaScript. It creates the primitive string type (string), which is also the default string type in TypeScript's type system.

// 原始字符串(推荐使用)
const txt1: string = "Hello TypeScript"; // 显式指定类型
const txt2 = "Hello JavaScript"; // 类型推导为 string

Method 2: String object (not recommended)

Usingnew String()creates the wrapper object type (String), which is essentially an object rather than a primitive value, bringing type confusion and performance loss.

// String 对象(不推荐)
const txtObj: String = new String("Hello Object"); // 类型为 String(对象)

String objects and string literals are different in type:

  • String literals are a primitive data typestring, used to directly store string values.
  • StringThe object is ofStringtype; it is actually an object, not the 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)
Type nature Primitive value Reference type (object)
Performance Efficient, no additional memory overhead Inefficient, creates object instances
Type checking (TypeScript) Conforms to TS basic type specifications Type mismatch (e.g., a string type variable cannot be assigned a String object)
Comparison method Compares values directly Compares reference addresses (requires valueOf() to get the primitive value)

Type compatibility between string literals and String objects

In TypeScript, the string literal type and the String object type are not fully compatible.

For example, a variable of type string cannot directly use the methods of a String object, and vice versa. Therefore, there is usually no need to use the String object.

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, comparison after converting the object to a primitive string

strLiteral is the primitive string type (string), while strObject is the 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, comparison after converting the object to a primitive string

String Object Properties

The following table lists the properties supported by the String object:

No. Property & 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:

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)  // 输出 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="[email protected]" // 添加属性 email
 console.log("员工号: "+emp.id) 
 console.log("员工姓名: "+emp.name) 
 console.log("员工邮箱: "+emp.email)

String Methods

The following table lists the methods supported by the String object:

No. Method & Description Example
1. charAt()

Returns the character at the specified position.

var str = new String("EXAMPLE"); 
console.log("str.charAt(0) 为:" + str.charAt(0)); // R
console.log("str.charAt(1) 为:" + str.charAt(1)); // U 
console.log("str.charAt(2) 为:" + str.charAt(2)); // N 
console.log("str.charAt(3) 为:" + str.charAt(3)); // O 
console.log("str.charAt(4) 为:" + str.charAt(4)); // O 
console.log("str.charAt(5) 为:" + str.charAt(5)); // B
2. charCodeAt()

Returns the Unicode value of the character at the specified position.

var str = new String("EXAMPLE"); 
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 a new string.

var str1 = new String( "EXAMPLE" ); 
var str2 = new String( "GOOGLE" ); 
var str3 = str1.concat( str2 ); 
console.log("str1 + str2 : "+str3) // EXAMPLEGOOGLE
4. indexOf()

Returns the position of the first occurrence of a specified string value in a string.

var str1 = new String( "EXAMPLE" ); 

var index = str1.indexOf( "OO" ); 
console.log("查找的字符串位置 :" + index );  // 3
5. lastIndexOf()

Searches a string from back to front and returns the position of the last occurrence, 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 in a locale-specific order.

var str1 = new String( "This is beautiful string" );
  
var index = str1.localeCompare( "This is beautiful string");  

console.log("localeCompare first :" + index );  // 0
7.

match()

Finds one or more regular expression matches.

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 a value matching 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 fragment 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 the starting index.

13. substring()

Extracts characters between two specified indices in a string.

var str = "EXAMPLE GOOGLE TAOBAO FACEBOOK"; 
console.log("(1,2): "    + str.substring(1,2));   // U
console.log("(0,10): "   + str.substring(0, 10)); // EXAMPLE 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 = "Example Google"; 
console.log(str.toLocaleLowerCase( ));  // example 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 = "Example Google"; 
console.log(str.toLocaleUpperCase( ));  // EXAMPLE GOOGLE
16. toLowerCase()

Converts a string to lowercase.

var str = "Example Google"; 
console.log(str.toLowerCase( ));  // example google
17. toString()

Returns a string.

var str = "Example"; 
console.log(str.toString( )); // Example
18. toUpperCase()

Converts a string to uppercase.

var str = "Example Google"; 
console.log(str.toUpperCase( ));  // EXAMPLE GOOGLE
19. valueOf()

Returns the primitive value of the specified string object.

var str = new String("Example"); 
console.log(str.valueOf( ));  // Example

Recommendations for Using String Objects

In TypeScript, using the String object is usually unnecessary. Using string literals directly is more efficient and conforms to TypeScript best practices:

  • Performance:StringThe object is a reference type, takes up more memory, and creating a new object each time has greater performance overhead.
  • Type safety: TypeScript encourages usingstringliteral types to keep the code concise and consistent.

If you do need to use methods of the String object, you can convert the object to a primitive string using the valueOf() method and then continue processing.

In general, TypeScript recommends using the string literal type 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."
Other Extensions