YouTip LogoYouTip

Ts String

In TypeScript, a string (String) is a fundamental data type used to represent textual data. It inherits and extends the string features of JavaScript while adding static type checking. ### Syntax var txt = new String("string"); Or in a simpler way: var txt = "string"; ### Two Creation Methods and Core Differences There are two ways to create strings in TypeScript, but they differ fundamentally in type, performance, and use cases: **Method 1: String Literal (Recommended)** This is the most commonly used and performant way in TypeScript/JavaScript. It creates a primitive string type (`string`), which is also the default string type in TypeScript's type system. ```typescript // Primitive string (recommended) const txt1: string = "Hello TypeScript"; // Explicitly specify type const txt2 = "Hello JavaScript"; // Type inferred as string **Method 2: String Object (Not Recommended)** Creating via `new String()` results in a wrapper object type (`String`). This is essentially an object, not a primitive value, which can lead to type confusion and performance overhead. ```typescript // String object (not recommended) const txtObj: String = new String("Hello Object"); // Type is String (object) A String object and a string literal are different in type: * A string literal is a primitive data type `string`, used to store string values directly. * A `String` object is of type `String`, which is actually an object, not a primitive string value. ## Example ```typescript 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 Essence | Primitive value | Reference type (object) | | Performance | Efficient, no extra 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 | Direct value comparison | Compares reference addresses (must use 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 methods of a String object, and vice versa. Therefore, in most cases, there is no need to use String objects. ## Example ```typescript 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, compares after converting object to 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 code is: ## Example ```javascript 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, compares after converting object to 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() { } | | 2. | length Returns the length of the string. | var uname = new String("Hello World"); console.log("Length " + uname.length); // Output 11 | | 3. | prototype Allows you to add properties and methods to the object. | function employee(id: number, name: string) { this.id = id; this.name = name; } var emp = new employee(123, "admin"); employee.prototype.email = "admin@"; // 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 the String object: | No. | Method & Description | Example | | --- | --- | --- | | 1. | charAt() Returns the character at the specified position. | var str = new String("TUTORIAL"); 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("TUTORIAL"); console.log("str.charCodeAt(0) is: " + str.charCodeAt(0)); // 82 console.log("str.charCodeAt(1) is: " + str.charCodeAt(1)); // 85 console.log("str.charCodeAt(2) is: " + str.charCodeAt(2)); // 78 console.log("str.charCodeAt(3) is: " + str.charCodeAt(3)); // 79 console.log("str.charCodeAt(4) is: " + str.charCodeAt(4)); // 79 console.log("str.charCodeAt(5) is: " + str.charCodeAt(5)); // 66 | | 3. | concat() Concatenates two or more strings and returns a new string. | var str1 = new String("TUTORIAL"); var str2 = new String("GOOGLE"); var str3 = str1.concat(str2); console.log("str1 + str2 : " + str3); // TUTORIALGOOGLE | | 4. | indexOf() Returns the position of the first occurrence of a specified string value in the string. | var str1 = new String("TUTORIAL"); var index = str1.indexOf("OO"); console.log("Search string position: " + index); // 3 | | 5. | lastIndexOf() Searches the string from the end and returns the position of the last occurrence, starting from the beginning (0). | var str1 = new String("This is string one and again string"); var index = str1.lastIndexOf("string"); console.log("lastIndexOf found last string position: " + index); // 29 index = str1.lastIndexOf("one"); console.log("lastIndexOf found last string position: " + index); // 15 | | 6. | localeCompare() Compares two strings using the 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 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 matched by 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 that matches 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 section 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 specified index. | | | 13. | substring() Extracts the characters between two specified indices in a string. | var str = "TUTORIAL GOOGLE TAOBAO FACEBOOK"; console.log("(1,2): " + str.substring(1, 2)); // U console.log("(0,10): " + str.substring(0, 10)); // TUTORIAL 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 (like Turkish) have locale-specific case mappings. | var str = "Tutorial Google"; console.log(str.toLocaleLowerCase()); // tutorial google | | 15. | toLocaleUpperCase() Converts a string to uppercase according to the host's locale. Only a few languages (like Turkish) have locale-specific case mappings. | var str = "Tutorial Google"; console.log(str.toLocaleUpperCase()); // TUTORIAL GOOGLE | | 16. | toLowerCase() Converts a string to lowercase. | var str = "Tutorial Google"; console.log(str.toLowerCase()); // tutorial google | | 17. | toString() Returns the string. | var str = "Tutorial"; console.log(str.toString()); // Tutorial | | 18. | toUpperCase() Converts a string to uppercase. | var str = "Tutorial Google"; console.log(str.toUpperCase()); // TUTORIAL GOOGLE | | 19. | valueOf() Returns the primitive value of the specified String object. | var str = new String("Tutorial"); console.log(str.valueOf()); // Tutorial | ### 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**: A `String` object is a reference type, which consumes more memory and has a larger performance overhead each time a new object is created. * **Type Safety**: TypeScript encourages the use of `string` literal types to maintain code simplicity and consistency. If you do need to use methods of a String object, you can convert the object to a primitive string using the `valueOf()` method 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 ```typescript 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."
← Ts TupleTs Number β†’