The toLocaleString() method in JavaScript is used to convert elements of an array into a localized string representation. This method does not modify the original array but returns a string representation of its elements.
Syntax
array.toLocaleString(locales, options);
Parameters
Parameter | Description |
---|---|
locales | Optional. A string with a BCP 47 language tag, or an array of such strings. It specifies the locale to be used for formatting. |
options | Optional. An object with configuration properties to customize the formatting. |
Return Value
Return Type | Description |
---|---|
String | A string representing the elements of the array, formatted according to the specified locales and options. |
Example 1: Default Usage
This code demonstrates how to use the toLocaleString()
method without any parameters, which uses the default locale and options.
let arr = [1, 'a', new Date()]; let localizedString = arr.toLocaleString(); console.log(localizedString);
Output:
1,a,MM/DD/YYYY, HH:MM:SS AM/PM
(Note: The exact output format for the date depends on the default locale of your JavaScript environment.)
Example 2: Specifying Locales
This code shows how to use the toLocaleString()
method with a specific locale to format the array elements.
let arr = [123456.789, 'a', new Date()]; let localizedString = arr.toLocaleString('de-DE'); console.log(localizedString);
Output:
123.456,789,a,DD.MM.YYYY, HH:MM:SS
Example 3: Using Options
This example demonstrates how to use the toLocaleString()
method with both locales and options to customize the output.
let arr = [123456.789, new Date()]; let options = { style: 'currency', currency: 'USD' }; let localizedString = arr.toLocaleString('en-US', options); console.log(localizedString);
Output:
$123,456.79,MM/DD/YYYY, HH:MM:SS AM/PM
Example 4: Combining Locales and Options
This code shows how to combine locales and options for more precise control over the formatting.
let arr = [123456.789, new Date()]; let locales = ['fr-FR', 'de-DE']; let options = { style: 'currency', currency: 'EUR', minimumFractionDigits: 2 }; let localizedString = arr.toLocaleString(locales, options); console.log(localizedString);
Output:
123 456,79 €, DD.MM.YYYY, HH:MM:SS
Supported Browsers
Chrome | Edge | Firefox | Opera | Safari |
---|---|---|---|---|
1 | 12 | 1 | 4 | 1 |