The Array.toLocaleString()
method is a built-in JavaScript function that converts the elements of an array into a localized string. This method is useful when working with date, number, or custom object data that should be represented in a locale-sensitive manner.
Syntax
arr.toLocaleString(locales, options);
Parameters
Parameter | Description |
---|---|
locales | (Optional) A string or array of strings that represents a BCP 47 language tag, specifies the locale. If omitted, the default locale of the runtime environment is used. |
options | (Optional) An object that specifies locale-specific formatting options. These options are passed to the toLocaleString() method of the individual elements. |
Return Value
The toLocaleString()
method returns a localized string representing the array’s elements, separated by a locale-specific separator.
Example 1: Using Default Locale
let arr = ['HTML', 'CSS', 'JavaScript']; let str = arr.toLocaleString(); console.log(str); // Output: "HTML,CSS,JavaScript"
Example 2: Formatting Numbers
let arr = [123456.789, 987654.321]; let str = arr.toLocaleString('en-US'); console.log(str); // Output: "123,456.789,987,654.321"
Example 3: Formatting Dates
let dates = [new Date('2024-01-01'), new Date('2024-12-31')]; let localizedString = dates.toLocaleString('en-GB'); console.log(localizedString); // Output: "01/01/2024,31/12/2024"
Example 4: Customizing Number Formatting
let prices = [1234.5, 5678.9]; let localizedString = prices.toLocaleString('de-DE', { style: 'currency', currency: 'EUR' }); console.log(localizedString); // Output: "1.234,50 €,5.678,90 €"
Example 5: Combining Data Types
let data = [12345.67, new Date('2024-01-01'), 'hello']; let localizedString = data.toLocaleString('en-US', { style: 'currency', currency: 'USD' }); console.log(localizedString); // Output: "$12,345.67,1/1/2024,hello"
Supported Browsers
Browser | Support |
---|---|
Chrome | 1+ |
Firefox | 1+ |
Safari | 1+ |
Edge | 12+ |
Opera | 4+ |
Internet Explorer | 5.5+ |