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-insensetive string comparison

If you want to do case insensitive comparison of the strings in JavaScript, you can turn both strings to lowercase and compare them using strict equality operator afterwards.

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 in 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 one in JavaScript, there’s a built-in function includes. Remember, the function contains exists in Java, but in JavaScript, it’s deprecated and replaced by includes.

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