To compare two strings in javascript

Compare Two Strings in JavaScript

JavaScript makes comparing strings easy. First, to compare if two strings are exactly equal, use === . Do not use == .

const str1 = '1st string'; const str2 = str1; const str3 = '2nd string'; str1 === str2; // true str1 === str3; // false // Always use `===`, because `==` can have some surprises '1' == 1; // true '2' == 2; // true

Using < and >compares strings lexicographically according to Unicode sort order. That means digits are always < uppercase letters, and uppercase letters are always < lowercase letters.

const str1 = '0'; const str2 = 'A'; const str3 = 'Z'; const str4 = 'a'; str1 < str2; // true str2 < str3; // true str3 < str4; // true

When comparing strings with length greater than 1, JavaScript compares character by character. If both strings start with the same character, JavaScript compares the 2nd characters of each string. The end of a string is always < any character.

// Empty string '' is ` const str1 = ''; const str2 = 'A'; const str3 = 'A1'; const str4 = 'Z0'; str1 < str2; // true str2 < str3; // true str3 < str4; // true

The < and >operators return false when comparing a string to a non-string:

1 < 'A'; // false 'A' < 1; // false null < 'A'; // false 'A' < null; // false undefined < 'A'; // false 'A' < undefined; // false

Sorting

By default, the Array#sort() function converts all values in an array to strings and then sorts them in Unicode sort order. The sort() function puts null and undefined values at the end of the array.

1 < 'A'; // false 'A' < 1; // false null < 'A'; // false 'A' < null; // false undefined < 'A'; // false 'A' < undefined; // false

Be careful when using = , because these use the same type coercion that == does.

More Fundamentals Tutorials

Источник

JavaScript String Comparison – How to Compare Strings in JS

Dillion Megida

Dillion Megida

JavaScript String Comparison – How to Compare Strings in JS

You may want to compare two strings to know which is higher or lower alphabetically or to see if they are equal.

You can do this in many ways. I’ll show you two of them in this article.

1. How to Compare Strings Using localeCompare

You can use the localeCompare method to compare two strings in the current locale. Here’s the syntax:

string1.localeCompare(string2) 
  • 1 if string1 is greater (higher in the alphabetical order) than string2
  • -1 if string1 is smaller (lower in the alphabetical order) than string2
  • 0 if string1 and string2 are equal in the alphabetical order

Here are some examples comparing two strings:

const string1 = "hello" const string2 = "world" const compareValue = string1.localeCompare(string2) // -1 

It gives -1 because, in the English locale, h in hello comes before w in the world (w is further down in the alphabetical order than h)

const string1 = "banana" const string2 = "back" const compareValue = string1.localeCompare(string2) // 1 

The comparison above gives 1 because, in the English locale, ban in banana comes after bac in back.

const string1 = "fcc" const string2 = "fcc" const string3 = "Fcc" const compareValue1 = string1.localeCompare(string2) // 0 const compareValue2 = string1.localeCompare(string3) // -1 

Comparing «fcc» and «fcc» gives 0 because they are equal in order. «fcc» and «Fcc» gives -1 because capital «F» is greater than small «f».

In some browsers, instead of -1, it may return -2 or some other negative value. So, do not depend on -1 or 1, instead on negative (less than 0) or positive (more than 0) values

2. How to Compare Strings Using Mathematical Operators

You can also use mathematical operators like greater than (>), less than (), and equal to when comparing strings.

Mathematical operators work similarly to localeCompare – by returning results based on the order of the characters in the string.

Using the previous examples:

const string1 = "hello" const string2 = "world" console.log(string1 > string2) // false 

string1 is not greater than string2 , because h comes before w, so it is less than.

const string1 = "banana" const string2 = "back" console.log(string1 > string2) // true 

string1 is greater than string2 because ban comes after back.

const string1 = "fcc" const string2 = "fcc" const string3 = "Fcc" console.log(string1 === string2) // true console.log(string1 < string3) // false 

string1 is equal to ( === ) string2 , but string1 is not less than string3 , which is in contrast to localeCompare .

With mathematical operators, "fcc" is greater than "Fcc", but with localeCompare , "fcc".localeCompare("Fcc")" returns -1 to show that "fcc" is less than "Fcc".

This behavior is one reason why I don't recommend using mathematical operators for comparing strings, even though it has the potential to do so.

So, for comparing strings, amongst the many ways there may be, using localCompare is an effective approach because it can be used for different languages.

Now you know an easy way to compare strings. Happy coding!

Dillion Megida

Dillion Megida

Developer Advocate and Content Creator passionate about sharing my knowledge on Tech. I simplify JavaScript / ReactJS / NodeJS / Frameworks / TypeScript / et al My YT channel: youtube.com/c/deeecode

If you read this far, tweet to the author to show them you care. Tweet a thanks

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

freeCodeCamp is a donor-supported tax-exempt 501(c)(3) charity organization (United States Federal Tax Identification Number: 82-0779546)

Our mission: to help people learn to code for free. We accomplish this by creating thousands of videos, articles, and interactive coding lessons - all freely available to the public. We also have thousands of freeCodeCamp study groups around the world.

Donations to freeCodeCamp go toward our education initiatives, and help pay for servers, services, and staff.

Источник

4 ways to compare strings in JavaScript

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 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 

Источник

String Equality in JavaScript – How to Compare Strings in JS

Joel Olawanle

Joel Olawanle

String Equality in JavaScript – How to Compare Strings in JS

When writing code or building a solution, you might need to compare two strings to see if they are the same before proceeding with an operation.

For example, when a user signs in, you'll want to compare the username the provide to the one in your database to see if they match.

In JavaScript, you can compare strings based on their value, length, character case, and lots more. In this article, you will learn how to compare strings in JavaScript.

How to Compare Strings in JavaScript With the Strict Equality Operator

Strict equality, or three equality ( === ) as its symbol implies, is a more detailed comparison than loose equality ( == ). It does not only check if the values are the same, but it also checks the operands:

let a = 12; let b = '12'; // Loose Equality console.log(a == b); // true // Strict Equality console.log(a === b); // false 

The strict operator is best used to compare strings in JavaScript because it checks to be sure both operands and values are the same and then returns a boolean result.

let string1 = "freeCodeCamp"; let string2 = "codeCamp"; console.log(string1 === string2); // false 

You can also directly compare a string to a variable and a string to a string if you wish:

let string1 = "freeCodeCamp"; console.log(string1 === "codeCamp"); // false console.log(string1 === "freeCodeCamp"); // true console.log("codeCamp" === "freeCodeCamp"); // false 

How to Perform Case Insensitive Comparison

When comparing with the strict equality operator, it is essential to know that this comparison is case sensitive. This means that freeCodeCamp is not equal to FreeCodeCamp because the first letter f is lowercase for one and uppercase for the other.

console.log("freeCodeCamp" === "FreeCodeCamp"); // false 

To avoid situations like this, you can perform case-insensitive comparisons. This means you convert the strings you are comparing to the same case:

let string1 = "freeCodeCamp"; let string2 = "FreeCodeCamp"; console.log(string1.toLowerCase() == string2.toLowerCase()); // true console.log(string1.toUpperCase() == string2.toUpperCase()); // true 

How to Compare Strings in JavaScript with the .length Property

In JavaScript, when you attach the .length property to a variable, it returns the string length:

let string1 = "freeCodeCamp"; console.log(string1.length); // 12 

This means you can use the length property to compare alongside either the equality (loose or strict), greater than (>), or less than (operator) to check if both lengths are the same or if one is more than the other.

let string1 = "freeCodeCamp"; let string2 = "codeCamp"; console.log(string1.length > string2.length); // true console.log(string1.length < string2.length); // false console.log(string1.length == string2.length); // false console.log(string1.length === string2.length); // false 

How to Compare Strings in JavaScript With the localeCompare() Method

The localeCompare() method can compare strings based on the current locale on the browser’s settings.

This method can be quite tricky, but it’s important to know that this method compares each character of both strings and returns a number which can be “-1”, “1”, or “0”.

  • -1: The left side string alphabetically comes before the right side string.
  • 1: The left side string alphabetically comes after the right side string.
  • 0: This means that both strings are equal.
let string1 = "freeCodeCamp"; let string2 = "codeCamp"; console.log(string1.localeCompare(string2)); // 1 

This returns “1” because “f” comes after “c” in the first character comparison.

let string1 = "freeCodeCamp"; let string2 = "codeCamp"; console.log(string2.localeCompare(string1)); // -1 

This now returns “-1” because “c” which is the first character of string2 on the left side comes before “f”. When both strings are equal, it returns “0” irrespective of their positions:

let string1 = "freeCodeCamp"; let string2 = "freeCodeCamp"; console.log(string2.localeCompare(string1)); // 0 

How to Perform Case Insensitive Comparison

It is also important to highlight that when you use the localeCompare() method, it is case sensitive. This means that it will return either “1” or “-1” depending on the position, even if both strings are the same but with a different case:

let string1 = "freeCodeCamp"; let string2 = "FreeCodeCamp"; console.log(string2.localeCompare(string1)); // 1 

You can fix this by introducing options and locale to the localeCompare() method. This method allows you to set a locale and also options that you can use to convert both strings to similar cases, so you perform a case-insensitive comparison.

let string1 = "freeCodeCamp"; let string2 = "FreeCodeCamp"; console.log(string2.localeCompare(string1, "en", < sensitivity: "base" >)); // 0 

You can read more about the localeCompare() method in the MDN documentation.

Wrapping Up

In this article, you have learned how to compare strings in JavaScript using the equality operators and the localeCompare() method.

Feel free to use your preferred methods, but you should mostly use localeCompare() when the comparison involves locale and some specific comparison that involves locale.

Источник

Читайте также:  Php default timezone warning
Оцените статью