An Interest In:
Web News this Week
- April 1, 2024
- March 31, 2024
- March 30, 2024
- March 29, 2024
- March 28, 2024
- March 27, 2024
- March 26, 2024
4 ways to Compare Strings in JavaScript
In this short JS tutorial, youll 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 theyre the same.
const s1 = 'learn';const s2 = 'today';console.log(s1 === 'learn'); // trueconsole.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" wont 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, well 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, theres a built-in function includes
. Remember, the function contains
exists in Java, but its deprecated and replaced by includes
in JavaScript.
const s1 = 'javascript';const s2 = 'python';console.log(s1.includes('script')); // trueconsole.log(s2.includes('script')); // falseconsole.log(s1.contains('java')) // ERROR! .contains is not a function
Read more JavaScript tutorials or Learn Full-Stack JS from scratch!
Original Link: https://dev.to/coderslang/4-ways-to-compare-strings-in-javascript-2ej9
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To