In this short JS tutorial, you’ll learn how to compare strings and see code examples.
Strict equality
To determine whether the strings are equal, you can use the strict equality operator ===
. It returns false
if the strings are different and true
, if they’re the same.
const s1 = 'learn';
const s2 = 'today';
console.log(s1 === 'learn'); // true
console.log(s1 === s2); // false
Comparing the strings using strict equality ===
always analyzes the case of the letters, meaning that capital letters are different from the small ones.
const s1 = 'javascript';
const s2 = 'Javascript';
console.log(s1 === s2); // false
Case-insensitive string comparison
If you want to do a case insensitive comparison of the strings in JavaScript, you can turn both strings to lowercase and compare them using a strict equality operator afterward.
const s1 = 'javascript';
const s2 = 'Javascript';
console.log(s1.toLowerCase() === s2.toLowerCase()); // true
Comparing the length of JavaScript strings
If you need to find which of two strings is longer, then the operators "greater than" and "lower than" won’t suit you well. They compare the characters of a string in alphanumeric order one by one and consider the length of the strings at the very end.
const s1 = 'javascript';
const s2 = 'node.js';
console.log(s1 > s2); // false
In JS, every string has the length
property. By comparing the value of this property in different strings, we’ll get to know which of them is longer.
const s1 = 'javascript';
const s2 = 'node.js';
console.log(s1.length > s2.length); // true
Check if a string contains another string
To check if one string is a substring of another in JavaScript, there’s a built-in function includes
. Remember, the function contains
exists in Java, but it’s deprecated and replaced by includes
in JavaScript.
const s1 = 'javascript';
const s2 = 'python';
console.log(s1.includes('script')); // true
console.log(s2.includes('script')); // false
console.log(s1.contains('java')) // ERROR! .contains is not a function
Read more JavaScript tutorials or Learn Full-Stack JS from scratch!
Top comments (2)
Title is a bit misleading. Instead of saying 4 ways of comparing strings, it should be 4 common string operations.
Your point makes sense, but for the total beginners, it's important to know that strict equality isn't the only way to compare two strings in JS.
And I wrote another article on the common string operations in JS