Sort special characters in Javascript (Æ)

I am trying to sort an array of objects based on object properties name. Some names begin with “Æ,” and I would like them to be sorted as if they were “Ae.” My current solution is as follows:

myArray.sort(function(a, b) {
  var aName = a.name.replace(/Æ/gi, 'Ae'),
      bName = b.name.replace(/Æ/gi, 'Ae');
  return aName.localeCompare(bName);
});

I feel that there should be a better way to handle this without having to manually replace each special character. Is it possible?

I do this in Node.js, if that matters.

+5
source share
1 answer

There is no simpler way. Unfortunately, even the method described in the question is too simple, at least if the portability is of any concern.

localeCompare , , ( JavaScript) . , , , , . , !

, , - elses, . , JavaScript, : Unicode, , , 'æ'.toUpperCase() Æ .

, , , ( ). , Ascii, , , ( Going Global JavaScript Globalize.js):

String.prototype.removeUmlauts = function () {
  return this.replace(/Ä/g,'A').replace(/Ö/g,'O').replace(/Ü/g,'U');
}; 
function alphabetic(str1, str2) {
  var a = str1.toUpperCase().removeUmlauts();
  var b = str2.toUpperCase().removeUmlauts();
  return a < b ? -1 : a > b ? 1 : 0;
}

, replace(/Æ/gi, 'Ae'), , , , . (, É E) , , , , , , É - Z. , , , , , , ( ).

+4

All Articles