Strings Comparison and Iteration

Learn about JavaScript string iteration and comparison with simple examples.

Loading...
Strings Comparison and Iteration

String Iteration

String iteration means going through each character of a string one by one.

In JavaScript, strings are iterable, which means you can loop through them using different techniques.

JavaScript provides the following ways to loop through strings.

1. for loop:

const str = "Learnify";
for (let i = 0; i < str.length; i++) {
  console.log(str[i]);
}
 
// Output:
 
// L
// e
// a
// r
// n
// i
// f
// y

Here, str[i] gives the character at index (position) i.

2. for...of loop:

This is a more modern and cleaner way and is often preferred for readability.

const str = "Learnify";
for (const char of str) {
  console.log(char);
}
 
// Output:
 
// L
// e
// a
// r
// n
// i
// f
// y

3. split() with forEach():

const str = "Learnify";
str.split("").forEach((char) => console.log(char));
 
// Output:
 
// L
// e
// a
// r
// n
// i
// f
// y
  • .split('') turns the string into an array of characters.
  • You can then use array methods like forEach() to loop through characters.

Why Iterate Strings?

  • To analyze or transform characters (e.g., count vowels, reverse, search).
  • Useful in algorithms and string manipulation tasks.

String Comparison

In JavaScript, you can compare strings using comparison operators like:

  • === (strict equality)
  • !== (strict inequality)
  • <, >, <=, >= (lexicographical comparison based on Unicode values)

Note: Comparisons are case-sensitive.

1. Using Equality Operators (=== and !==):

The === operator checks if both strings are exactly the same, including the same characters in the same order and case.

console.log("apple" === "apple"); // Output: true (both strings are identical)
console.log("apple" === "Apple"); // Output: false ('a' and 'A' are different (case matters))
console.log("hello" !== "Hello"); // Output: true (different casing)

2. Lexicographical Comparison (<, >, <=, >=):

Strings can be compared alphabetically using < and >. JavaScript uses Unicode code points to determine order.

console.log("apple" > "Apple"); // Output: true

Here, "a" (Unicode 97) is greater than "A" (Unicode 65), so "apple" is considered greater than "Apple".

console.log("banana" < "cherry"); // Output: true ('b' comes before 'c')
console.log("zoo" > "Zoo"); // Output: true ('z' > 'Z')

How the String Comparison Works Internally

When comparing strings:

  1. JavaScript compares the first characters of each string.
  2. If they’re the same, it compares the next character, and so on.
  3. It stops at the first difference.
console.log("abc" < "abd"); // Output: true ('c' < 'd')
console.log("abc" < "ab"); // Output: false ('abc' is longer)

localeCompare() for Locale-Sensitive and Case-Insensitive Comparisons

The .localeCompare() method in JavaScript allows you to compare two strings in a way that respects language and region-specific rules, known as locales, such as case, accents, and alphabet order.

This is especially useful when sorting or comparing strings in multi-language applications.

Syntax:

referenceString.localeCompare(compareString, locale, options);
  • referenceString: The string you're comparing from.
  • compareString: The string you're comparing to.
  • locale: A BCP 47 language tag (e.g. "en", "fr", "de") (optional).
  • options: To customize comparison (e.g. case sensitivity) (optional).

Return Values:

  • -1: reference string comes before
  • 0: strings are equivalent
  • 1: reference string comes after

Example:

console.log("apple".localeCompare("banana")); // Output: -1
console.log("banana".localeCompare("banana")); // Output: 0
console.log("cherry".localeCompare("banana")); // Output: 1

Default comparison is case-sensitive:

console.log("a".localeCompare("A")); // Output: 1 or -1 (depending on system locale)

In many locales, lowercase letters come after uppercase ones, so "a" is usually greater than "A".

Case-insensitive comparison with sensitivity: 'base':

You can use sensitivity: 'base' to ignore case and accents.

console.log("a".localeCompare("A", undefined, { sensitivity: "base" })); // Output: 0
  • 'base' treats "a" and "A" as equal

  • Other options include:

    • 'accent': ignores case, but not accents
    • 'case': ignores accents, but not case
    • 'variant' (default): strictest (case + accent sensitive)

Why Use localeCompare()?

  • It respects locale-specific sorting rules.
  • Handles case and accent sensitivity cleanly.
  • Better than ===, <, > when you care about user language expectations.
  • Ideal for internationalized apps, alphabetical UI lists, and searching.

Support my work!