Javascript - Strings

| Comments

Sorting Strings

Javascript has a native method sort that allows sorting arrays. Doing a simple array.sort() each value will be treated as a string and sorted alphabetically. Also you can create your own custom sorting function passing it how argument.

1
2
['Shanghai', 'New York', 'Mumbai', 'Buenos Aires'].sort();
// ["Buenos Aires", "Mumbai", "New York", "Shanghai"]

But when you try order an array of non ASCII characters like this ['é', 'a', 'ú', 'c'], you will obtain an strange result ['c', 'e', 'á', 'ú']. That happens because sort works only with english language.

See the next example:

1
2
3
4
5
6
7
// Spanish
['único','árbol', 'cosas', 'fútbol'].sort();
// ["cosas", "fútbol", "árbol", "único"] // bad order

// German
['Woche', 'wöchentlich', 'wäre', 'Wann'].sort();
// ["Wann", "Woche", "wäre", "wöchentlich"] // bad order

Fortunately exists two ways to avoid this mistake localeCompare and Intl.Collator provided by ECMAScript Internationalization API.

Both methods have his own custom parameters in order to configure it for work adequately.

Using localeCompare()

1
2
3
4
5
6
7
8
9
['único','árbol', 'cosas', 'fútbol'].sort(function (a, b) {
  return a.localeCompare(b);
});
// ["árbol", "cosas", "fútbol", "único"]

['Woche', 'wöchentlich', 'wäre', 'Wann'].sort(function (a, b) {
  return a.localeCompare(b);
});
// ["Wann", "wäre", "Woche", "wöchentlich"]

Using Intl.Collator()

1
2
3
4
5
['único','árbol', 'cosas', 'fútbol'].sort(Intl.Collator().compare);
// ["árbol", "cosas", "fútbol", "único"]

['Woche', 'wöchentlich', 'wäre', 'Wann'].sort(Intl.Collator().compare);
// ["Wann", "wäre", "Woche", "wöchentlich"]
  • For each method you can customize the location.
  • According Firefox Intl.Collator it’s more fast for compare large numbers of strings.

So remember when you are working with arrays of string in another language that not is english, use this methods to avoid unexpected errors.

ES6 Template Strings

As of ES6, JS now has template strings as an alternative to the classic end quotes strings.

Normal string

1
2
3
4
5
var firstName = 'John';
var middleName = 'Paul';
var lastName = 'Jones';
console.log('My name is ' + firstName + ' ' + middleName + ' ' + lastName);
// My name is John Paul Jones

Template String

1
2
3
4
5
var firstName = 'John';
var middleName = 'Paul';
var lastName = 'Jones';
console.log(`My name is ${firstName} ${middleName} ${lastName}`);
// My name is John Paul Jones

You can do Multi-line strings without \n and simple logic (ie 2+3) inside ${} in Template String.

You are also able to to modify the output of template strings using a function; they are called Tagged template strings for example usages of tagged template strings.

You may also want to read to understand template strings more

Comments