Typescript String - Complete tutorials with examples

You can check another post on Fix for Object is possibly null

TypeScript String Object Data Type

A string contains a group of characters saved under the variable name of the String object. Understanding basic operations on strings is essential.

In this tutorial, we will explore various methods and examples.

Basic Syntax of String Object Creation

var variable_name = new string("CloudHadoop");

There are multiple ways to create a string object in TypeScript:

var cloudVariableName = new string("CloudHadoop");
let newStringExample = "123";

A string is one of the data types in TypeScript. It’s crucial not to confuse it with the String object.

The Difference Between string and String A string is a type in JavaScript, while a String is in TypeScript.

How to Check for Empty or Null String in TypeScript?

How to check The empty or Null of a String in typescript?

In this example, we return true if the string is numeric. Strings can also contain numbers in single quotes. To check if a string is numeric, first, convert it to a number and then use the isNaN method to validate.

function checkSuppliedStringisNumeric(strParameter: string | number): boolean {
  return !isNaN(Number(strParameter.toString()));
}
console.log(checkSuppliedStringisNumeric("123")); // outputs true
console.log(checkSuppliedStringisNumeric("123abc")); // outputs false
console.log(checkSuppliedStringisNumeric("abc")); // outputs false*+++

How to remove whitespaces in String object?

Removing whitespaces from a string object is a common requirement. It can be achieved using various methods. The trim() method removes spaces from the beginning and end of a word. Alternatively, regular expressions can be used to remove all spaces.

console.log("cloud hadoop".replace(/\s/g, "")); // outputs cloudhadoop
console.log("cloud hadoop".trim()); // outputs cloud hadoop

console.log(" cloud hadoop ".replace(/\s/g, "")); // outputs cloudhadoop
console.log(" cloud hadoop ".trim()); // outputs cloud hadoop

String for each iteration Example

First, let’s see how to create a string array in TypeScript. The string type is declared after the variable followed by a semicolon.

String iteration can be achieved using forEach, for-in, or for-of loop functionality.

var msgs: string[] = ['string1', 'string2', 'string3'];

// forEach String array iteration example
msgs.forEach(function(entry) {
     console.log(entry);
});

// For-In String array iteration example
for(const msg in msgs) {
        console.log(msgs[msg]);
}

// For-Of String array iteration example
for (const m of msgs) {
    console.log(m);
}

// Plain For loop String array iteration example
for (let i = 0; i < msgs.length; ++i) {
    console.log (msgs[i]);
}

There are multiple ways to loop through a string array. for-in and plain for loop use index mechanisms to iterate, but the order is not guaranteed. Meanwhile, forEach and for-of iterate over each string array object.

TypeScript: Split String into an Array of Substrings Example

Using the substring function, we can split a string using spaces.

var message = "[cloud,hadoop,examples,tutorials]";
function splitStringIntoArray(input) {
  var messages = input.substring(1, input.length - 1).split(", ");
  return messages;
}
document.body.innerHTML =
  splitStringIntoArray(message)[0] +
  " " +
  splitStringIntoArray(message)[1] +
  " " +
  splitmessages(message)[2];

How to convert String to a Boolean example

Strings can contain true or false values. This function returns a Boolean value if a valid string is passed; otherwise, it returns undefined.

function transferToBoolean(input: string): boolean | undefined {
  try {
    return JSON.parse(input);
  } catch (e) {
    return undefined;
  }
}

console.log(transferToBoolean("true")); // true
console.log(transferToBoolean("false")); // false
console.log(transferToBoolean("invalid")); // undefined

String type methods

TypeScript provides various inbuilt methods for manipulating string content

MethodDescription
concatJoining the two strings and returning one output string
toLowerCasereturn the lowercase of the output string
toUpperCasereturn the uppercase of the output string
toStringreturns the string content
substringreturns the substring of starting index to the end index
charAtreturn character at the specified index in a string
slicereturn the portion of a string

Related posts:

Conclusion

To summarize, we’ve learned about the string class in TypeScript, including its methods and example use cases.