w3resource

JavaScript: Test case insensitive (except special Unicode characters) string comparison

JavaScript String: Exercise-37 with Solution

Case-Insensitive Compare

Write a JavaScript function to test case-insensitive (except special Unicode characters) string comparison.

Test Data:
console.log(compare_strings('abcd', 'AbcD'));
true
console.log(compare_strings('ABCD', 'Abce'));
false

Visual Presentation:

JavaScript: Test case insensitive (except special Unicode characters) string comparison

Sample Solution:

JavaScript Code:

// Define a function named compare_strings that takes two string parameters: str1 and str2
function compare_strings(str1, str2) {
    // Convert both strings to uppercase and check if they are equal
    var areEqual = str1.toUpperCase() === str2.toUpperCase();
    // Return the result of the comparison
    return areEqual;
}

// Test the function by comparing two pairs of strings and print the results
console.log(compare_strings('abcd', 'AbcD')); // Output: true
console.log(compare_strings('ABCD', 'Abce')); // Output: false

Output:

true
false

Explanation:

In the exercise above,

JavaScript code defines a function called "compare_strings()" that takes two string parameters 'str1' and 'str2'. Inside the function:

  • Both input strings 'str1' and 'str2' are converted to uppercase using the "toUpperCase()" method.
  • The equality of the two uppercase strings is checked using the '===' operator, and the result is stored in the variable 'areEqual'.
  • Finally, the function returns the boolean value 'areEqual', which indicates whether the two input strings are equal, regardless of their case.

Flowchart:

Flowchart: JavaScript- Test case insensitive (except special Unicode characters) string comparison.

Live Demo:

See the Pen JavaScript Test case insensitive (except special Unicode characters) string comparison-string-ex-37 by w3resource (@w3resource) on CodePen.


For more Practice: Solve these Related Problems:

  • Write a JavaScript function that compares two strings for equality, ignoring differences in letter case.
  • Write a JavaScript function that converts both strings to lowercase before comparison.
  • Write a JavaScript function that uses localeCompare() with sensitivity set to base to perform case-insensitive comparisons.
  • Write a JavaScript function that returns true if two strings match regardless of case and false otherwise.

Go to:


PREV : Zero-Fill Number.
NEXT : Case-Insensitive Search.

Improve this sample solution and post your code through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.