How To Check If Two Strings Are Equal In Typescript

How To Check If Two Strings Are Equal In Typescript

Knowing how to check if two strings are equal in Typescript will help you a lot when working with the string like you can check input from use. Using equality operator is one of those methods to do it. Let’s go into detail now.

Check if two strings are equal in Typescript

Use equality operator

The equality operator(==) helps you check if two strings are equal and then returns a boolean.

Example:

const str1:string = 'WooLa'
const str2:string = 'WooLa'
let result: boolean

result = str1 == str2
console.log(result)
result = (str1 == str2)
console.log(result) 

Output:

[LOG]: true 
[LOG]: true

Here if my string has whitespace, then the result will be false.

Example:

const str1:string = 'WooLa'
const str2:string = 'WooLa'
const str3:string = ' WooLa'
let result: boolean
let result2: boolean

result = (str1 == str2)
result2= (str1 == str3)

console.log(result) 
console.log(result2)

Output:

[LOG]: true 
[LOG]: false

But with the equality operator in Typescript will try to convert and compare the different types.

Example:

const str1:string = '1'
const str2:number = 1
let result: boolean

result = (str1 == str2) // This condition will always return 'false' since the types' string' and 'number' have no overlap
console.log(result)

Output:

[LOG]: true

Typescript also warned us, but it still works if we try to run the code.

Use strict equality operator

To solve the problem with type, we can use strict equality operator(===). The strict equality operator is like the equality operator, but it will never deal with different types. So I recommend you always use a strict equality operator.

Example:

const str1:string = '1'
const str2:number = 1
let result: boolean

result = (str1 === str2) //This condition will always return 'false' since the types' string' and 'number' have no overlap.
console.log(result)

Output:

[LOG]: false

The strict equality operators also provides us with the IsStrictlyEqual semantic(!==) to check if two strings are not equal.

Example:

const str1:string = 'Hello'
const str2:string = 'World'
let result: boolean

result1 = (str1 !== str2)
console.log(result1)

result2 = (str1 === str2)
console.log(result2)

Output:

[LOG]: true 
[LOG]: false

You can also apply the equality operator inside conditional logic code.

Example:

const str1:string = 'Hello'
const str2:string = 'Hello'

if (str1===str2){
  console.log("Hello World")
}

Output:

[LOG]: "Hello World"

Summary

In this tutorial, we showed and explained how to check if two strings are equal in Typescript. You can use the equality operator or strict equality operator. You can also apply it to your conditional logic code. Good luck for you!

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *