TypeScript -String Data Type

Type Script History

A string is a sequence of numbers, letters, special characters and arithmetic values or combination of all.

  

        let firstName: string = "Praveen"; // using double quotes
        let lastName: string = 'Singh'; // using single quotes

        console.log(firstName);
        console.log(lastName);
    

Template strings are used for embedding expressions into strings.

  

        let fullName: string = `Bob Bobbington`;
        let age: number = 37;
        let sentence: string = `Hello, my name is ${ fullName }. I'll be ${ age + 1 } years old next month.`;
        console.log(sentence);
    

String Methods

String Methods

Method

Description

charAt()

Returns the character at given index.

charCodeAt()

Returns a number indicating the Unicode of the character at the specified index.

concat()

Joins two or more strings, and returns a new string.

endsWith()

Checks whether a string ends with a specified substring.

fromCharCode()

Converts Unicode values to characters.

includes()

Checks whether a string contains the specified substring.

indexOf()

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

lastIndexOf()

Returns the index of the last occurrence of the specified value in a string.

localeCompare()

check two strings in the current locale.

match()

Matches a string against a regular expression, and returns an array of all matches.

repeat()

Returns a new string which contains the specified number of copies of the original string.

replace()

Replaces the occurrences of a string or pattern inside a string with another string, and return a new string without modifying the original string.

search()

Searches a string against a regular expression, and returns the index of the first match.

slice()

Extracts a portion of a string and returns it as a new string.

split()

Splits a string object into an array of substrings.

startsWith()

Checks whether a string begins with a specified substring.

substr()

Extracts the part of a string between the start index and a number of characters after it.

substring()

Extracts the part of a string between the start and end indexes.

toLocaleLowerCase()

Converts a string to lowercase letters, according to host machine's current locale.

toLocaleUpperCase()

Converts a string to uppercase letters, according to host machine's current locale.

toLowerCase()

Converts a string to lowercase letters.

toString()

returns a string value of a specified object.

toUpperCase()

Converts a string to uppercase letters.

trim()

Remove/Trim whitespace from the beginning and end of the string.

valueOf()

Returns the primitive value of a specified String object.

1. charAt(x)

Returns the character at given index(y).

  

        let str: string = 'Hello TypeScript';
        str.charAt(0);	 // returns 'H'
        str.charAt(2); 	// returns 'l'
        "Hello World".charAt(2); returns 'l'
    

2. charCodeAt(x)

Returns a number indicating the Unicode of the character at the specified index

  

        let str1: string = 'Hello TypeScript';
        console.log(str1.charCodeAt(0)); ;       // output : 72
        console.log(str1.charCodeAt(2)); ;       //  output : 108
        console.log("Hello TypeScript".charCodeAt(2));     //  output : 108
    

3. concat(x1, x1,x3…)

Combine/Add one or more strings (arguments x1, x2, x3 etc) into the existing one and returns the combined string. Original strings are not changed.

  

        let str1 = 'Hello';
        let str2 = 'TypeScript';

        console.log(str1.concat(' ', str2));     //Hello TypeScript

        console.log(str2.concat(', ', str1));    //TypeScript, Hello
    

4. endsWith()

The endsWith() method check whether a string ends with a specified string parameter and return true or false.

  

        let str1 = 'Hello world, welcome to the TypeScript';

        console.log(str1.endsWith('TypeScript', 38));        //true
        console.log(str1.endsWith('TypeScript'));            //true
        console.log(str1.endsWith('welcome'));              //false

        // Typescript compiler “error:- error TS2339: Property 'endsWith' does not exist on type 'string'.” Then run compile the typescript file using below command
        // compile it using :  tsc --target ES6  filename

    

5. fromCharCode(x1, x2,x3…)

Returns a string using the specified sequence of Unicode values (arguments x1, x2,x3 etc).

  

        console.log(String.fromCharCode(74,79,72,78))       //JOHN

        console.log(String.fromCharCode(68,79,69))          //DOE
    

6. includes()

The includes() method check a string contains the characters of a specified string and return true or false.

  

        The includes() method check a string contains the characters of a specified string and return true or false.

        let str1 = 'Hello world, welcome to the TypeScript';

        console.log(str1.includes("world"));        // true
        console.log(str1.includes("John"));         // false
    

7. indexOf()

The indexOf() method returns the index of the first occurrence of a specified argument value in a string. This method returns -1 if the value is not found in search string.

  

        let str1 = 'Hello world, welcome to the TypeScript';
        console.log(str1.indexOf("world"));        // 6
        console.log(str1.indexOf("John"));         // -1
    

8. lastIndexOf()

This method returns the index of the last occurrence of a specified argument value in a string. This method returns -1 if the value is not found in search string.

  

        let str1 = 'Hello world, welcome to the TypeScript world';

        console.log(str1.lastIndexOf("world"));        // 39
        console.log(str1.lastIndexOf("John"));         // -1
    

9. localeCompare()

This method compares two strings in the current locale and return a number.

  

        let str1 = 'réservé';   // with accents lowercase
        let  str2 = 'RESERVE';  // no accents  uppercase

        console.log(str1.localeCompare(str2)); // output: 1
        console.log(str1.localeCompare(str2, 'en', {sensitivity: 'base'}));  //output: 0
    

10. match()

This method searches a string for a match against passed argument regular expression and returns the matches in the form of array object.

  

        let str1 = 'Hello world, welcome to the TypeScript world';

        let uperCaseregex = /[A-Z]/g;
        let result = str1.match(uperCaseregex);

        console.log(result);            // [ 'H', 'T', 'S' ]
    

11. repeat()

This repeat(n) methed repeat the string n times provided in argument and return combined/concatenated string.

  

        let str1: string = 'Hello TypeScript';

        let result = console.log(str1.repeat(20)); // Repeat the str1 string 20 times
        console.log(result);

        //Hello TypeScriptHello TypeScriptHello TypeScriptHello TypeScriptHello TypeScriptHello TypeScriptHello TypeScriptHello TypeScriptHello TypeScriptHello TypeScriptHello TypeScriptHello TypeScriptHello
        // TypeScriptHello TypeScriptHello TypeScriptHello TypeScriptHello TypeScriptHello TypeScriptHello TypeScriptHello TypeScript
    

12. replace()

This method takes two arguments searchValue/regexExpression and newValue. If searchValue found in a string, then replace the searchValue with newValue. Original/source string will be not change

  

        let str1 = 'Hello world, welcome to the TypeScript world';
        let regexExp =/world/gi;

        let result = str1.replace(regexExp,'John');
        let result1 = str1.replace('world','John Doe')

        console.log(result);           //Hello John, welcome to the TypeScript John
        console.log(result1);          // Hello John Doe, welcome to the TypeScript world
    

13. search()

This method searches a string for a specified argument value and returns the position/index of the match argument value. If search value not found then return -1.

  

        let str1 = 'Hello world, welcome to the TypeScript world';
        let regexExp =/world/gi;

        let result = str1.search(regexExp);
        let result1 = str1.search('world')
        let result2 = str1.search('john')

        console.log(result);           // 6
        console.log(result1);          // 6
        console.log(result2);          // -1
    

14. slice()

The slice() method takes two arguments start position and end position, return the value from start position to end position without changing the original string.

  


        let str1 = 'Hello world, welcome to the TypeScript world';

        console.log(str1.slice(6));                   //      world, welcome to the TypeScript world
        console.log(str1.slice(0,5));                 //      Hello
        console.log(str1.slice(13,20));               //      welcome
        console.log(str1.slice(-5));                  //      world
        console.log(str1.slice(-16,-5));              //      TypeScript
    

15. split()

split() method take the argument separator, split the string into an array and return the string array.

  

        let str1 = 'Hello world, welcome to the TypeScript world';

        console.log(str1.split(" "))           //[ 'Hello', 'world,', 'welcome', 'to', 'the', 'TypeScript', 'world' ]
        console.log(str1.split("to"))          // [ 'Hello world, welcome ', ' the TypeScript world' ]
        console.log('John Doe'.split(""))

        //  [
        //         'J', 'o', 'h',
        //         'n', ' ', 'D',
        //         'o', 'e'
        //       ]
    

16. startsWith()

The startsWith() method check whether a string begin with the specified argument string, return true if value at starting position else return false.

  

        let str1 = 'Hello world, welcome to the TypeScript world';

        console.log(str1.startsWith('Hello'));                  //true
        console.log(str1.startsWith('Hello',10));               //false

        console.log(str1.startsWith('John'));                   //false
        console.log(str1.startsWith('world',6));                 //true
    

17. substr()

The substr() Extracts the part of a string between the start index and a number of characters after it.

  

        let str1 = 'Hello world, welcome to the TypeScript world';

        console.log(str1.substr(0,5));                  //Hello
        console.log(str1.substr(6,6));                  //world,
        console.log(str1.substr(0));                  //Hello world, welcome to the TypeScript world
        console.log(str1.substr(6));                  //world, welcome to the TypeScript world
    

18. substring(

The substring() fetch the characters from a string, between two specified position/index, returns the new string.

  

        let str1 = 'Hello world, welcome to the TypeScript world';

        console.log(str1.substring(0,5));                  //Hello
        console.log(str1.substring(6,11));                  //world,
        console.log(str1.substring(0));                  //Hello world, welcome to the TypeScript world
        console.log(str1.substring(6));                  //world, welcome to the TypeScript world
    

19. toLocaleLowerCase()

The toLocaleLowerCase() method convert the string to lower case using current specified local

  

        let str1 = 'Hello world, welcome to the TypeScript world';

        console.log(str1.toLocaleLowerCase('en-US'));           //hello world, welcome to the typescript world
        console.log(str1.toLocaleLowerCase('de-de'));           //hello world, welcome to the typescript world
        console.log(str1.toLocaleLowerCase('hi'));              //hello world, welcome to the typescript world
    

20. toLocaleUpperCase()

The toLocaleUpperCase() method returns the calling string value converted to upper case, according to any locale-specific case mappings.

  

        var city = 'istanbul';

        console.log(city.toLocaleUpperCase('en-US'));
        // expected output: "ISTANBUL"

        console.log(city.toLocaleUpperCase('TR'));
        // expected output: "İSTANBUL"

    

21. toLowerCase()

The toLowerCase() method convert the string into lowercase and return the converted string.

  

        let str1 = 'Hello world, welcome to the TypeScript world';

        console.log(str1.toLowerCase());           //   hello world, welcome to the typescript world
        let toUpperCaseString = 'JOHN DOE'.toLowerCase()
        console.log(toUpperCaseString);                 //john doe

    

22. toString()

The toString() method returns a string value of a specified object.

  

        let str1 = new String('Hello TypeScript')
        console.log(str1);              //[String: 'Hello TypeScript']
        console.log(str1.toString());   //Hello TypeScript
    

23. toUpperCase()

The toUpperCase() method convert the string into upper case and return the converted string(upper case).

  


        let str1 = 'Hello world, welcome to the TypeScript world';

        console.log(str1.toUpperCase());           //  HELLO WORLD, WELCOME TO THE TYPESCRIPT WORLD
        let toUpperCaseString = 'john doe'.toUpperCase()
        console.log(toUpperCaseString);                 //JOHN DOE
    

25. trim()

The trim() method removes whitespace from start and end(both side), return the string trimmed string .

  

        let str1 = ' Hello TypeScript '
        let result = str1.trim();
        console.log(result);                    //  Hello TypeScript

        console.log(' John Doe '.trim());         //  John Doe
    

26. valueOf()

The valueOf() method returns the primitive value of a specified String object.

  

        let str1 = new String('Hello TypeScript')
        console.log(str1);                    //  [String: 'Hello TypeScript']

        console.log(str1.valueOf());      // Hello TypeScript

        console.log(' John Doe '.valueOf());         //  John Doe