String Functions in TypeScript

The standard library’s string methods provide many useful string-related functions. Here are some examples to give you a sense of these methods.

// We'll use console.log for our output
const p = console.log;

function main() {
    // Here's a sample of the methods available on strings.
    // In TypeScript, these are methods on the string object itself,
    // so we call them directly on the string.

    p("Includes:   ", "test".includes("es"));
    p("Count:      ", "test".split("t").length - 1);
    p("StartsWith: ", "test".startsWith("te"));
    p("EndsWith:   ", "test".endsWith("st"));
    p("IndexOf:    ", "test".indexOf("e"));
    p("Join:       ", ["a", "b"].join("-"));
    p("Repeat:     ", "a".repeat(5));
    p("Replace:    ", "foo".replace(/o/g, "0"));
    p("Replace:    ", "foo".replace("o", "0"));
    p("Split:      ", "a-b-c-d-e".split("-"));
    p("ToLower:    ", "TEST".toLowerCase());
    p("ToUpper:    ", "test".toUpperCase());
}

main();

To run the program, save it as string-functions.ts and use ts-node (assuming you have TypeScript and ts-node installed):

$ ts-node string-functions.ts
Includes:   true
Count:      2
StartsWith: true
EndsWith:   true
IndexOf:    1
Join:       a-b
Repeat:     aaaaa
Replace:    f00
Replace:    f0o
Split:      [ 'a', 'b', 'c', 'd', 'e' ]
ToLower:    test
ToUpper:    TEST

Note that TypeScript, being a superset of JavaScript, uses the built-in String methods. Some methods like Count don’t have direct equivalents, so we’ve used a combination of split and length to achieve the same result. The Replace method in TypeScript only replaces the first occurrence by default, so we’ve shown both the global replacement (using a regular expression) and the single replacement.