TypeScript string object

TypeScript string object:

A TypeScript String object represents a sequence of characters.

TypeScript String Object Properties:

Property Description
constructor It returns a reference to the String function that created the object.
length It returns the length of the string.
prototype It allows us to add properties and methods to an object.

TypeScript String Object Methods:

Method Description
charAt() It returns the character at the specified index.
charCodeAt() It returns a number indicating the Unicode value of the character at the given index.
concat() It combines the text of two strings and returns a new string.
indexOf() It returns the index within the calling String object of the first occurrence of the specified value, or -1 if not found.
lastIndexOf() It returns the index within the calling String object of the last occurrence of the specified value, or -1 if not found.
localeCompare() It returns a number indicating whether a reference string comes before or after or is the same as the given string in sort order.
match() It is used to match a regular expression against a string.
replace() It is used to find a match between a regular expression and a string, and to replace the matched substring with a new substring.
search() It executes the search for a match between a regular expression and a specified string.
slice() It extracts a section of a string and returns a new string.
split() It splits a String object into an array of strings by separating the string into substrings.
substr() It returns the characters in a string beginning at the specified location through the specified number of characters.
substring() It returns the characters in a string between two indexes into the string.
toLocaleLowerCase() The characters within a string are converted to lower case while respecting the current locale.
toLocaleUpperCase() The characters within a string are converted to upper case while respecting the current locale.
toLowerCase() It returns the calling string value converted to lower case.
toString() It returns a string representing the specified object.
toUpperCase() It returns the calling string value converted to uppercase.
valueOf() It returns the primitive value of the specified object.

How to create TypeScript string object:

  • By using string literals.
  • By using String() constructor.

By using number literals:

When we create a number literal browser automatically converts it to Number object.

Syntax:

var str1:string = “value”;

Example:

function stringTest(str:string):void{
  console.log(str); 
}
var str:string = "Sahdev";
stringTest(str);

Try it:

JS Bin on jsbin.com

By using String() constructor:

We can create a TypeScript String object by using String() constructor.

Syntax:

var str1:string = new String(value);

Example:

function stringTest(str:string):void{
  console.log(str); 
}
var str:string = new String("Richi");
stringTest(str);