Write a function that will check if two given characters are the same case javascript

Many careers in tech pay over $100,000 per year. With help from Career Karma, you can find a training program that meets your needs and will set you up for a long-term, well-paid career in tech.

By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.

Sep 4, 2020

Comparing two strings in JavaScript is easy: just use ===. But what if you want to treat uppercase and lowercase letters as equal, so is equivalent to ?

The most basic way to do case insensitive string comparison in JavaScript is using either the toLowerCase() or toUpperCase() method to make sure both strings are either all lowercase or all uppercase.

const str1 = ''; const str2 = ''; str1 === str2; str1.toLowerCase() === str2.toLowerCase();

Using localeCompare()

JavaScript's String#localeCompare() method gives you more fine-grained control over string comparison. For example, you can also compare two strings ignoring diacritics. Below is how you can do case-insensitive string comparison using localeCompare():

const str1 = ''; const str2 = ''; str1 === str2; str1.localeCompare(str2, undefined, { sensitivity: 'accent' });

The localeCompare() function is particularly useful if you want to sort an array of strings, ignoring case:

const strings = ['Alpha', 'Zeta', 'alpha', 'zeta']; strings.sort((str1, str2) => str1.localeCompare(str2, undefined, { sensitivity: 'accent' })); strings;

Don't Use Regular Expressions

You may be tempted to compare two strings using regular expressions and JavaScript regexp's i flag.

const str1 = ''; const str2 = ''; new RegExp('^' + str1 + '$', 'i').test(str2);

However, using this approach, you need to be careful to escape special regular expression characters. For example, the below comparison fails, whereas it would succeed using toLowerCase() or localeCompare().

const str1 = '[hello]'; const str2 = '[Hello]'; new RegExp('^' + str1 + '$', 'i').test(str2);

You're better off using toLowerCase() or localeCompare() than using a regular expression.

More Fundamentals Tutorials

Strict equality compares two values for equality. Neither value is implicitly converted to some other value before being compared. If the values have different types, the values are considered unequal. If the values have the same type, are not numbers, and have the same value, they're considered equal. Finally, if both values are numbers, they're considered equal if they're both not NaN and are the same value, or if one is +0 and one is -0.

const num = 0; const obj = new String("0"); const str = "0"; console.log(num === num); console.log(obj === obj); console.log(str === str); console.log(num === obj); console.log(num === str); console.log(obj === str); console.log(null === undefined); console.log(obj === null); console.log(obj === undefined);

Strict equality is almost always the correct comparison operation to use. For all values except numbers, it uses the obvious semantics: a value is only equal to itself. For numbers it uses slightly different semantics to gloss over two different edge cases. The first is that floating point zero is either positively or negatively signed. This is useful in representing certain mathematical solutions, but as most situations don't care about the difference between +0 and -0, strict equality treats them as the same value. The second is that floating point includes the concept of a not-a-number value, NaN, to represent the solution to certain ill-defined mathematical problems: negative infinity added to positive infinity, for example. Strict equality treats NaN as unequal to every other value — including itself. (The only case in which (x !== x) is true is when x is NaN.)

Besides ===, strict equality is also used by array index-finding methods including Array.prototype.indexOf(), Array.prototype.lastIndexOf(), TypedArray.prototype.index(), TypedArray.prototype.lastIndexOf(), and case-matching. This means you cannot use indexOf(NaN) to find the index of a NaN value in an array, or use NaN as a case value in a switch statement and make it match anything.

console.log([NaN].indexOf(NaN)); switch (NaN) { case NaN: console.log("Surprise"); }

Write a function that will check if two given characters are the same case javascript
Akande Olalekan Toheeb

The String is zero or more characters embraced with a single or double quote in JavaScript. Anything can be put inside a string to be stored for future use.

A developer may need to compare two strings while writing codes to check various things that need to be done.

How do we get this done when JavaScript itself is case-sensitive by default?

We can make a case-insensitive String comparison by using the following three ways in JavaScript:

  1. The abstract equality == or strict equality === operator.
  2. The .localeCompare() method.
  3. Regular expression.

Note: We’ll discuss only equality operators in this shot.

Using the equality operators

The equality operators compare two strings if they are equal.

let stringA = 'Bird'; let stringB = 'bird'; if(stringA == stringB){ console.log("The strings have the same characters."); } else { console.log("The strings ain't the same."); }

Here’s the explanation of the above code:

  • Lines 1 and 2: We create two variables, stringA and StringB, and assign some strings to them. StringA starts with a capital letter while stringB starts with a small letter, but both have the same character.

  • Line 4: We use an if/else statement to compare the two strings. It returns a sentence to the console if the string is the same and another sentence if the string is not the same.

We check the console and The strings ain't the same. is printed to the console. Because JavaScript is case-sensitive, it doesn’t recognize both strings with the same characters.

How do we solve this?

First, we need to compare both strings in lowercase or uppercase using .toLowerCase and .toUpperCase before comparison.

This will give a perfect comparison.

let stringA = 'This is a Bird'; let stringB = 'this is A birD'; if(stringA.toLocaleUpperCase = stringB.toUpperCase){ console.log('The strings are perfectly the same.'); } else { console.log('The strings ain\'t the same'); } // or betterstill /* if(stringA.toLocaleLowerCase = stringB.toLowerCase){ console.log('This strings are perfectly the same.'); } else { console.log('The strings ain\'t the same'); } */

  • Lines 1 and 2: We create two variables and assign them with strings of identical letters but in different cases.

We compare these two strings using the equality operator.

  • Line 3: We create an if/else statement. In this condition (the brackets after if), the two strings are converted to uppercase. So it has to be identical before comparison (why? because JavaScript is case sensitive). Then the code blocks to execute are created.

When we check the console, it prints The strings are perfectly the same because the condition is met.

The code above clearly solves the problem as it compares the two strings perfectly.

In this shot, you learned how to compare case insensitive strings using the equality operator.

RELATED TAGS

javascript

string

communitycreator