DEV Community

VivekSinh Rajput
VivekSinh Rajput

Posted on

String methods in TS often used in developement...

Here's a rundown of commonly used string methods in TypeScript for web development, along with examples that address real-world problems:

1. trim()

  • Purpose: Remove whitespace from both ends of a string.
  • Use case: Cleaning up user input, especially from text fields.
let userInput = "   Some text with spaces   ";
let cleanedInput = userInput.trim();
console.log(cleanedInput); // "Some text with spaces"
Enter fullscreen mode Exit fullscreen mode

2. toLowerCase() and toUpperCase()

  • Purpose: Convert string case.
  • Use case: Normalizing text for comparison (case-insensitive search), making text uniform for UI consistency.
let userName = "John Doe";
let searchQuery = "john";
if (userName.toLowerCase() === searchQuery.toLowerCase()) {
    console.log("User found!");
}
Enter fullscreen mode Exit fullscreen mode

3. split()

  • Purpose: Split a string into an array of substrings based on a separator.
  • Use case: Parsing CSV data, URL parameters, or any delimited data.
// Parsing a CSV string
let csvData = "name,age,city\nJohn,30,New York";
let rows = csvData.split("\n");
let headers = rows[0].split(",");
console.log(headers); // ['name', 'age', 'city']
Enter fullscreen mode Exit fullscreen mode

4. join() (used in conjunction with split())

  • Purpose: Combine array elements into a string.
  • Use case: Creating strings from array data, like forming a URL from parameters.
let urlParams = ["user=John", "age=30"];
let queryString = urlParams.join("&");
console.log(queryString); // "user=John&age=30"
Enter fullscreen mode Exit fullscreen mode

5. replace()

  • Purpose: Replace occurrences of a substring with another string.
  • Use case: Formatting text, sanitizing user input, or applying simple templating.
// Simple text templating
let template = "Hello, {name}!";
let result = template.replace("{name}", "Alice");
console.log(result); // "Hello, Alice!"
Enter fullscreen mode Exit fullscreen mode

6. includes()

  • Purpose: Check if a string contains another string.
  • Use case: Validation, search functionality.
let email = "test@example.com";
if (email.includes("@")) {
    console.log("Valid email format");
}
Enter fullscreen mode Exit fullscreen mode

7. startsWith() and endsWith()

  • Purpose: Check if a string begins or ends with specified characters.
  • Use case: Filename validation, checking URL paths, or implementing simple routing logic.
let path = "/api/v1/users";
if (path.startsWith("/api")) {
    console.log("This is an API endpoint");
}

let fileName = "report.pdf";
if (fileName.endsWith(".pdf")) {
    console.log("PDF file detected");
}
Enter fullscreen mode Exit fullscreen mode

8. substring() or slice()

  • Purpose: Extract parts of a string.
  • Use case: Extracting specific parts of strings like dates, times, or parsing identifiers.
let dateString = "2023-01-01T12:00:00Z";
let datePart = dateString.substring(0, 10);  // "2023-01-01"
console.log(datePart);
Enter fullscreen mode Exit fullscreen mode

9. indexOf() or lastIndexOf()

  • Purpose: Find the position of the first (or last) occurrence of a specified value in a string.
  • Use case: Locating markers within strings for parsing or processing.
let sentence = "The quick brown fox jumps over the lazy dog";
let firstThe = sentence.indexOf("the");  // 0
let lastThe = sentence.lastIndexOf("the");  // 36
console.log(firstThe, lastThe);
Enter fullscreen mode Exit fullscreen mode

10. match() with RegEx

  • Purpose: Search for a match between a regular expression and a string.
  • Use case: Complex string pattern matching or validation like email, phone number validations.
let text = "My email is example@email.com";
let emailRegex = /\S+@\S+\.\S+/;
let emailMatch = text.match(emailRegex);
console.log(emailMatch ? emailMatch[0] : "No email found"); // "example@email.com"
Enter fullscreen mode Exit fullscreen mode

These methods are foundational in handling text manipulation, which is ubiquitous in web development for tasks ranging from simple text formatting to complex data parsing. Remember, TypeScript adds type safety to these operations, which can help catch errors at compile-time rather than runtime.

Top comments (0)