How to Sort Alphanumeric Strings with JavaScript?

A guide on sorting alphanumeric strings with JavaScript.

Sometimes, we want to sort alphanumeric strings with JavaScript.

In this article, we’ll look at how to sort alphanumeric strings with JavaScript.

String.prototype.localeCompare

We can use the string localeCompare method to compare strings so we can sort them.

For instance, we can write:

const arr = ["123asd", "19asd", "12345asd", "asd123", "asd12"];
const sorted = arr.sort((a, b) => {
  return a.localeCompare(b, undefined, {
    numeric: true,
    sensitivity: "base",
  });
});
console.log(sorted);

We call localeCompare to compare a and b naturally.

We set numeric to true to compare the numerical part of a and b .

sensitivity is set to 'base' to compare the case and the alphabet.

Therefore, sorted is:

["19asd", "123asd", "12345asd", "asd12", "asd123"];

Use Intl.Collator

Also, we can use the Intl.Collator constructor to create a collator instance that has the compare method to compare 2 strings.

For instance, we can write:

const arr = ["123asd", "19asd", "12345asd", "asd123", "asd12"];
const collator = new Intl.Collator(undefined, {
  numeric: true,
  sensitivity: "base",
});
const sorted = arr.sort((a, b) => {
  return collator.compare(a, b);
});
console.log(sorted);

The options are the same as localeCompare.

compare takes the 2 strings we want to compare.

Then sorted is the same result as before.

Conclusion

This is how we can sort alphanumeric strings naturally with native JavaScript methods.

Enjoyed this article?

Share it with your network to help others discover it

Continue Learning

Discover more articles on similar topics