How to use the String object in TypeScript

1 Answer

0 votes
/**
 * TypeScript String Example
 * -------------------------
 * Demonstrates:
 * - Creating strings
 * - Common string methods
 * - String searching
 * - String manipulation
 * - Template literals
 * - Custom functions
 * - Type annotations
 */


/*
Common operations include
-------------------------
trim()
toUpperCase()
toLowerCase()
includes()
startsWith()
endsWith()
slice()
replace()
split()
repeat()
*/

"use strict";

/**
 * Converts text to Title Case.
 *
 * Example:
 * "hello world" -> "Hello World"
 *
 * @param text Input string
 * @returns Title-cased string
 */
function toTitleCase(text: string): string {
    return text
        .toLowerCase()
        .split(" ")
        .map((word: string): string => {
            if (word.length === 0) {
                return "";
            }

            return (
                word.charAt(0).toUpperCase() +
                word.slice(1)
            );
        })
        .join(" ");
}

/**
 * Counts the number of words in a string.
 *
 * @param text Input string
 * @returns Number of words
 */
function countWords(text: string): number {
    return text
        .trim()
        .split(/\s+/)
        .filter((word: string): boolean => word.length > 0)
        .length;
}

/**
 * Reverses a string.
 *
 * @param text Input string
 * @returns Reversed string
 */
function reverseString(text: string): string {
    return text.split("").reverse().join("");
}

// ----------------------------------------------------
// Create a string
// ----------------------------------------------------

const message: string = "  Hello TypeScript World!  ";

console.log("=== Original String ===");
console.log(message);

// ----------------------------------------------------
// Trim whitespace
// ----------------------------------------------------

const trimmedMessage: string = message.trim();

console.log("\n=== trim() ===");
console.log(trimmedMessage);

// ----------------------------------------------------
// Length
// ----------------------------------------------------

const length: number = trimmedMessage.length;

console.log("\n=== length ===");
console.log(length);

// ----------------------------------------------------
// Character Access
// ----------------------------------------------------

console.log("\n=== Character Access ===");

const firstCharacter: string = trimmedMessage[0];
const secondCharacter: string = trimmedMessage.charAt(1);

console.log(firstCharacter);
console.log(secondCharacter);

// ----------------------------------------------------
// Case Conversion
// ----------------------------------------------------

console.log("\n=== Case Conversion ===");

const uppercase: string =
    trimmedMessage.toUpperCase();

const lowercase: string =
    trimmedMessage.toLowerCase();

console.log(uppercase);
console.log(lowercase);

// ----------------------------------------------------
// Search Methods
// ----------------------------------------------------

console.log("\n=== Search Methods ===");

const containsTypeScript: boolean =
    trimmedMessage.includes("TypeScript");

const startsWithHello: boolean =
    trimmedMessage.startsWith("Hello");

const endsWithWorld: boolean =
    trimmedMessage.endsWith("World!");

console.log(containsTypeScript);
console.log(startsWithHello);
console.log(endsWithWorld);

// ----------------------------------------------------
// indexOf()
// ----------------------------------------------------

const position: number =
    trimmedMessage.indexOf("TypeScript");

console.log("\n=== indexOf() ===");
console.log(position);

// ----------------------------------------------------
// Extract Text
// ----------------------------------------------------

console.log("\n=== slice() ===");

const extractedText: string =
    trimmedMessage.slice(6, 16);

console.log(extractedText);

// ----------------------------------------------------
// Replace Text
// ----------------------------------------------------

console.log("\n=== replace() ===");

const updatedMessage: string =
    trimmedMessage.replace(
        "TypeScript",
        "JavaScript"
    );

console.log(updatedMessage);

// ----------------------------------------------------
// Split Text
// ----------------------------------------------------

console.log("\n=== split() ===");

const words: string[] =
    trimmedMessage.split(" ");

console.log(words);

// ----------------------------------------------------
// Repeat Text
// ----------------------------------------------------

console.log("\n=== repeat() ===");

const separator: string = "-".repeat(25);

console.log(separator);

// ----------------------------------------------------
// Template Literals
// ----------------------------------------------------

console.log("\n=== Template Literals ===");

const language: string = "TypeScript";
const version: string = "5.x";

const description: string =
    `${language} Version ${version}`;

console.log(description);

// ----------------------------------------------------
// Custom Function Examples
// ----------------------------------------------------

console.log("\n=== Custom Functions ===");

const titleCaseText: string =
    toTitleCase("learning typescript is fun");

const wordCount: number =
    countWords(trimmedMessage);

const reversedText: string =
    reverseString(trimmedMessage);

console.log("Title Case:", titleCaseText);
console.log("Word Count:", wordCount);
console.log("Reversed :", reversedText);


/*
run:

=== Original String ===
  Hello TypeScript World!  

=== trim() ===
Hello TypeScript World!

=== length ===
23

=== Character Access ===
H
e

=== Case Conversion ===
HELLO TYPESCRIPT WORLD!
hello typescript world!

=== Search Methods ===
true
true
true

=== indexOf() ===
6

=== slice() ===
TypeScript

=== replace() ===
Hello JavaScript World!

=== split() ===
[ 'Hello', 'TypeScript', 'World!' ]

=== repeat() ===
-------------------------

=== Template Literals ===
TypeScript Version 5.x

=== Custom Functions ===
Title Case: Learning Typescript Is Fun
Word Count: 3
Reversed : !dlroW tpircSepyT olleH

*/

 



answered Oct 16 by avibootz
...