repo_id
stringlengths 22
103
| file_path
stringlengths 41
147
| content
stringlengths 181
193k
| __index_level_0__
int64 0
0
|
---|---|---|---|
data/mdn-content/files/en-us/web/javascript/reference/global_objects/int32array | data/mdn-content/files/en-us/web/javascript/reference/global_objects/int32array/int32array/index.md | ---
title: Int32Array() constructor
slug: Web/JavaScript/Reference/Global_Objects/Int32Array/Int32Array
page-type: javascript-constructor
browser-compat: javascript.builtins.Int32Array.Int32Array
---
{{JSRef}}
The **`Int32Array()`** constructor creates {{jsxref("Int32Array")}} objects. The contents are initialized to `0`.
## Syntax
```js-nolint
new Int32Array()
new Int32Array(length)
new Int32Array(typedArray)
new Int32Array(object)
new Int32Array(buffer)
new Int32Array(buffer, byteOffset)
new Int32Array(buffer, byteOffset, length)
```
> **Note:** `Int32Array()` can only be constructed with [`new`](/en-US/docs/Web/JavaScript/Reference/Operators/new). Attempting to call it without `new` throws a {{jsxref("TypeError")}}.
### Parameters
See [`TypedArray`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#parameters).
### Exceptions
See [`TypedArray`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray#exceptions).
## Examples
### Different ways to create an Int32Array
```js
// From a length
const int32 = new Int32Array(2);
int32[0] = 42;
console.log(int32[0]); // 42
console.log(int32.length); // 2
console.log(int32.BYTES_PER_ELEMENT); // 4
// From an array
const x = new Int32Array([21, 31]);
console.log(x[1]); // 31
// From another TypedArray
const y = new Int32Array(x);
console.log(y[0]); // 21
// From an ArrayBuffer
const buffer = new ArrayBuffer(32);
const z = new Int32Array(buffer, 4, 4);
console.log(z.byteOffset); // 4
// From an iterable
const iterable = (function* () {
yield* [1, 2, 3];
})();
const int32FromIterable = new Int32Array(iterable);
console.log(int32FromIterable);
// Int32Array [1, 2, 3]
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `Int32Array` in `core-js`](https://github.com/zloirock/core-js#ecmascript-typed-arrays)
- [JavaScript typed arrays](/en-US/docs/Web/JavaScript/Guide/Typed_arrays) guide
- {{jsxref("TypedArray")}}
- {{jsxref("ArrayBuffer")}}
- {{jsxref("DataView")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects | data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/index.md | ---
title: Intl
slug: Web/JavaScript/Reference/Global_Objects/Intl
page-type: javascript-namespace
browser-compat: javascript.builtins.Intl
---
{{JSRef}}
The **`Intl`** namespace object contains several constructors as well as functionality common to the internationalization constructors and other language sensitive functions. Collectively, they comprise the ECMAScript Internationalization API, which provides language sensitive string comparison, number formatting, date and time formatting, and more.
## Description
Unlike most global objects, `Intl` is not a constructor. You cannot use it with the [`new` operator](/en-US/docs/Web/JavaScript/Reference/Operators/new) or invoke the `Intl` object as a function. All properties and methods of `Intl` are static (just like the {{jsxref("Math")}} object).
The internationalization constructors as well as several language sensitive methods of other constructors (listed under [See also](#see_also)) use a common pattern for identifying locales and determining the one they will actually use: they all accept `locales` and `options` arguments, and negotiate the requested locale(s) against the locales they support using an algorithm specified in the `options.localeMatcher` property.
### locales argument
The `locales` argument is used to determine the locale used in a given operation. The JavaScript implementation examines `locales`, and then computes a locale it understands that comes closest to satisfying the expressed preference. `locales` may be:
- `undefined` (or omitted): The implementation's default locale will be used.
- A locale: A locale identifier or an [`Intl.Locale`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Locale) object that wraps a locale identifier.
- A list of locales: Any other value, that will be converted into an object and then treated as an array of locales.
In the latter two cases, the actual locale used is the best-supported locale determined by [locale negotiation](#locale_identification_and_negotiation). If a locale identifier is not a string or an object, a {{jsxref("TypeError")}} is thrown. If a locale identifier is a string that's syntactically invalid, a {{jsxref("RangeError")}} is thrown. If a locale identifier is well-formed but the implementation doesn't recognize it, it is ignored and the next locale in the list is considered, eventually falling back to the system's locale. However, you shouldn't rely on a particular locale name being ignored, because the implementation may add data for any locale in the future. For example, `new Intl.DateTimeFormat("default")` uses the implementation's default locale only because `"default"` is syntactically valid but not recognized as any locale.
A locale identifier is a string that consists of:
1. A language subtag with 2–3 or 5–8 letters
2. A script subtag with 4 letters {{optional_inline}}
3. A region subtag with either 2 letters or 3 digits {{optional_inline}}
4. One or more variant subtags (all of which must be unique), each with either 5–8 alphanumerals or a digit followed by 3 alphanumerals {{optional_inline}}
5. One or more BCP 47 extension sequences {{optional_inline}}
6. A private-use extension sequence {{optional_inline}}
Each subtag and sequence are separated by hyphens. Locale identifiers are case-insensitive {{Glossary("ASCII")}}. However, it's conventional to use title case (the first letter is capitalized, successive letters are lower case) for script subtags, upper case for region subtags, and lower case for everything else. For example:
- `"hi"`: Hindi (language)
- `"de-AT"`: German (language) as used in Austria (region)
- `"zh-Hans-CN"`: Chinese (language) written in simplified characters (script) as used in China (region)
- `"en-emodeng"`: English (language) in the "Early modern English" dialect (variant)
Subtags identifying languages, scripts, regions (including countries), and (rarely used) variants are registered in the [IANA Language Subtag Registry](https://www.iana.org/assignments/language-subtag-registry/language-subtag-registry). This registry is periodically updated over time, and implementations may not always be up to date, so don't rely too much on subtags being universally supported.
BCP 47 extension sequences consist of a single digit or letter (other than `"x"`) and one or more two- to eight-letter or digit subtags separated by hyphens. Only one sequence is permitted for each digit or letter: `"de-a-foo-a-foo"` is invalid. BCP 47 extension subtags are defined in the [Unicode CLDR Project](https://github.com/unicode-org/cldr/tree/main/common/bcp47). Currently only two extensions have defined semantics:
- The `"u"` (Unicode) extension can be used to request additional customization of `Intl` API objects. Examples:
- `"de-DE-u-co-phonebk"`: Use the phonebook variant of the German sort order, which interprets umlauted vowels as corresponding character pairs: ä → ae, ö → oe, ü → ue.
- `"th-TH-u-nu-thai"`: Use Thai digits (๐, ๑, ๒, ๓, ๔, ๕, ๖, ๗, ๘, ๙) in number formatting.
- `"ja-JP-u-ca-japanese"`: Use the Japanese calendar in date and time formatting, so that 2013 is expressed as the year 25 of the Heisei period, or 平成 25.
- `"en-GB-u-ca-islamic"`: use British English with the Islamic (Hijri) calendar, where the Gregorian date 14 October, 2017 is the Hijri date 24 Muharram, 1439.
- The `"t"` (transformed) extension indicates transformed content: for example, text that was translated from another locale. No `Intl` functionality currently considers the `"t"` extension. However, this extension sometimes contains a nested locale (with no extensions): for example, the transformed extension in `"de-t-en"` contains the locale identifier for English. If a nested locale is present, it must be a valid locale identifier. For example, because `"en-emodeng-emodeng"` is invalid (because it contains a duplicate `emodeng` variant subtag), `"de-t-en-emodeng-emodeng"` is also invalid.
Finally, a private-use extension sequence using the letter `"x"` may appear, followed by one or more one- to eight-letter or digit subtags separated by hyphens. This allows applications to encode information for their own private use, that will be ignored by all `Intl` operations.
### options argument
The `options` argument must be an object with properties that vary between constructors and functions. If the `options` argument is not provided or is undefined, default values are used for all properties.
One property is supported by all language sensitive constructors and functions: The `localeMatcher` property, whose value must be a string `"lookup"` or `"best fit"` and which selects one of the locale matching algorithms described below.
### Locale identification and negotiation
The list of locales specified by the `locales` argument, after Unicode extensions have been removed from them, is interpreted as a prioritized request from the application. The runtime compares it against the locales it has available and picks the best one available. Two matching algorithms exist: the `"lookup"` matcher follows the Lookup algorithm specified in [BCP 47](https://datatracker.ietf.org/doc/html/rfc4647#section-3.4); the `"best fit"` matcher lets the runtime provide a locale that's at least, but possibly more, suited for the request than the result of the Lookup algorithm. If the application doesn't provide a `locales` argument, or the runtime doesn't have a locale that matches the request, then the runtime's default locale is used. The matcher can be selected using a property of the `options` argument (see below).
If the selected locale identifier had a Unicode extension sequence, that extension is now used to customize the constructed object or the behavior of the function. Each constructor or function supports only a subset of the keys defined for the Unicode extension, and the supported values often depend on the locale identifier. For example, the `"co"` key (collation) is only supported by {{jsxref("Intl.Collator")}}, and its `"phonebk"` value is only supported for German.
## Static properties
- {{jsxref("Intl.Collator")}}
- : Constructor for collators, which are objects that enable language-sensitive string comparison.
- {{jsxref("Intl.DateTimeFormat")}}
- : Constructor for objects that enable language-sensitive date and time formatting.
- {{jsxref("Intl.DisplayNames")}}
- : Constructor for objects that enable the consistent translation of language, region and script display names.
- {{jsxref("Intl.DurationFormat")}} {{experimental_inline}}
- : Constructor for objects that enable locale-sensitive duration formatting.
- {{jsxref("Intl.ListFormat")}}
- : Constructor for objects that enable language-sensitive list formatting.
- {{jsxref("Intl.Locale")}}
- : Constructor for objects that represents a Unicode locale identifier.
- {{jsxref("Intl.NumberFormat")}}
- : Constructor for objects that enable language-sensitive number formatting.
- {{jsxref("Intl.PluralRules")}}
- : Constructor for objects that enable plural-sensitive formatting and language-specific rules for plurals.
- {{jsxref("Intl.RelativeTimeFormat")}}
- : Constructor for objects that enable language-sensitive relative time formatting.
- {{jsxref("Intl.Segmenter")}}
- : Constructor for objects that enable locale-sensitive text segmentation.
- `Intl[@@toStringTag]`
- : The initial value of the [`@@toStringTag`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/toStringTag) property is the string `"Intl"`. This property is used in {{jsxref("Object.prototype.toString()")}}.
## Static methods
- {{jsxref("Intl.getCanonicalLocales()")}}
- : Returns canonical locale names.
- {{jsxref("Intl.supportedValuesOf()")}}
- : Returns a sorted array containing the supported unique calendar, collation, currency, numbering systems, or unit values supported by the implementation.
## Examples
### Formatting dates and numbers
You can use `Intl` to format dates and numbers in a form that's conventional for a specific language and region:
```js
const count = 26254.39;
const date = new Date("2012-05-24");
function log(locale) {
console.log(
`${new Intl.DateTimeFormat(locale).format(date)} ${new Intl.NumberFormat(
locale,
).format(count)}`,
);
}
log("en-US"); // 5/24/2012 26,254.39
log("de-DE"); // 24.5.2012 26.254,39
```
### Using the browser's preferred language
Instead of passing a hardcoded locale name to the `Intl` methods, you can use the user's preferred language provided by {{domxref("navigator.language")}}:
```js
const date = new Date("2012-05-24");
const formattedDate = new Intl.DateTimeFormat(navigator.language).format(date);
```
Alternatively, the {{domxref("navigator.languages")}} property provides a sorted list of the user's preferred languages. This list can be passed directly to the `Intl` constructors to implement preference-based fallback selection of locales. The [locale negotiation](#locale_identification_and_negotiation) process is used to pick the most appropriate locale available:
```js
const count = 26254.39;
const formattedCount = new Intl.NumberFormat(navigator.languages).format(count);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("String.prototype.localeCompare()")}}
- {{jsxref("Number.prototype.toLocaleString()")}}
- {{jsxref("Date.prototype.toLocaleString()")}}
- {{jsxref("Date.prototype.toLocaleDateString()")}}
- {{jsxref("Date.prototype.toLocaleTimeString()")}}
- {{domxref("navigator.language")}}
- {{domxref("navigator.languages")}}
- [The ECMAScript Internationalization API](https://norbertlindenberg.com/2012/12/ecmascript-internationalization-api/index.html) by Norbert Lindenberg (2012)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl | data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/segmenter/index.md | ---
title: Intl.Segmenter
slug: Web/JavaScript/Reference/Global_Objects/Intl/Segmenter
page-type: javascript-class
browser-compat: javascript.builtins.Intl.Segmenter
---
{{JSRef}}
The **`Intl.Segmenter`** object enables locale-sensitive text segmentation, enabling you to get meaningful items (graphemes, words or sentences) from a string.
{{EmbedInteractiveExample("pages/js/intl-segmenter.html")}}
## Constructor
- {{jsxref("Intl/Segmenter/Segmenter", "Intl.Segmenter()")}}
- : Creates a new `Intl.Segmenter` object.
## Static methods
- {{jsxref("Intl/Segmenter/supportedLocalesOf", "Intl.Segmenter.supportedLocalesOf()")}}
- : Returns an array containing those of the provided locales that are supported without having to fall back to the runtime's default locale.
## Instance properties
These properties are defined on `Intl.Segmenter.prototype` and shared by all `Intl.Segmenter` instances.
- {{jsxref("Object/constructor", "Intl.Segmenter.prototype.constructor")}}
- : The constructor function that created the instance object. For `Intl.Segmenter` instances, the initial value is the {{jsxref("Intl/Segmenter/Segmenter", "Intl.Segmenter")}} constructor.
- `Intl.Segmenter.prototype[@@toStringTag]`
- : The initial value of the [`@@toStringTag`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/toStringTag) property is the string `"Intl.Segmenter"`. This property is used in {{jsxref("Object.prototype.toString()")}}.
## Instance methods
- {{jsxref("Intl/Segmenter/resolvedOptions", "Intl.Segmenter.prototype.resolvedOptions()")}}
- : Returns a new object with properties reflecting the locale and granularity options computed during initialization of this `Intl.Segmenter` object.
- {{jsxref("Intl/Segmenter/segment", "Intl.Segmenter.prototype.segment()")}}
- : Returns a new iterable [`Segments`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Segmenter/segment/Segments) instance representing the segments of a string according to the locale and granularity of this `Intl.Segmenter` instance.
## Examples
### Basic usage and difference from String.prototype.split()
If we were to use [`String.prototype.split(" ")`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split) to segment a text in words, we would not get the correct result if the locale of the text does not use whitespaces between words (which is the case for Japanese, Chinese, Thai, Lao, Khmer, Myanmar, etc.).
```js example-bad
const str = "吾輩は猫である。名前はたぬき。";
console.table(str.split(" "));
// ['吾輩は猫である。名前はたぬき。']
// The two sentences are not correctly segmented.
```
```js example-good
const str = "吾輩は猫である。名前はたぬき。";
const segmenterJa = new Intl.Segmenter("ja-JP", { granularity: "word" });
const segments = segmenterJa.segment(str);
console.table(Array.from(segments));
// [{segment: '吾輩', index: 0, input: '吾輩は猫である。名前はたぬき。', isWordLike: true},
// etc.
// ]
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/segmenter | data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/segmenter/segmenter/index.md | ---
title: Intl.Segmenter() constructor
slug: Web/JavaScript/Reference/Global_Objects/Intl/Segmenter/Segmenter
page-type: javascript-constructor
browser-compat: javascript.builtins.Intl.Segmenter.Segmenter
---
{{JSRef}}
The **`Intl.Segmenter()`** constructor creates {{jsxref("Intl.Segmenter")}} objects.
{{EmbedInteractiveExample("pages/js/intl-segmenter.html")}}
## Syntax
```js-nolint
new Intl.Segmenter()
new Intl.Segmenter(locales)
new Intl.Segmenter(locales, options)
```
> **Note:** `Intl.Segmenter()` can only be constructed with [`new`](/en-US/docs/Web/JavaScript/Reference/Operators/new). Attempting to call it without `new` throws a {{jsxref("TypeError")}}.
### Parameters
- `locales` {{optional_inline}}
- : A string with a BCP 47 language tag or an {{jsxref("Intl.Locale")}} instance, or an array of such locale identifiers. For the general form and interpretation of the `locales` argument, see [the parameter description on the `Intl` main page](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#locales_argument).
- `options` {{optional_inline}}
- : An object containing the following properties, in the order they are retrieved (all of them are optional):
- `localeMatcher`
- : The locale matching algorithm to use. Possible values are `"lookup"` and `"best fit"`; the default is `"best fit"`. For information about this option, see [Locale identification and negotiation](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#locale_identification_and_negotiation).
- `granularity`
- : How granularly should the input be split. Possible values are:
- `"grapheme"` (default)
- : Split the input into segments at grapheme cluster (user-perceived character) boundaries, as determined by the locale.
- `"word"`
- : Split the input into segments at word boundaries, as determined by the locale.
- `"sentence"`
- : Split the input into segments at sentence boundaries, as determined by the locale.
### Return value
A new [`Intl.Segmenter`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Segmenter) instance.
### Exceptions
- {{jsxref("RangeError")}}
- : Thrown if `locales` or `options` contain invalid values.
## Examples
### Basic usage
The following example shows how to count words in a string using the Japanese language (where splitting the string using `String` methods would have given an incorrect result).
```js
const text = "吾輩は猫である。名前はたぬき。";
const japaneseSegmenter = new Intl.Segmenter("ja-JP", { granularity: "word" });
console.log(
[...japaneseSegmenter.segment(text)].filter((segment) => segment.isWordLike)
.length,
);
// 8, as the text is segmented as '吾輩'|'は'|'猫'|'で'|'ある'|'。'|'名前'|'は'|'たぬき'|'。'
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/segmenter | data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/segmenter/segment/index.md | ---
title: Intl.Segmenter.prototype.segment()
slug: Web/JavaScript/Reference/Global_Objects/Intl/Segmenter/segment
page-type: javascript-instance-method
browser-compat: javascript.builtins.Intl.Segmenter.segment
---
{{JSRef}}
The **`segment()`** method of {{jsxref("Intl.Segmenter")}} instances segments a string according to the locale and granularity of this `Intl.Segmenter` object.
{{EmbedInteractiveExample("pages/js/intl-segmenter-prototype-segment.html")}}
## Syntax
```js-nolint
segment(input)
```
### Parameters
- `input`
- : The text to be segmented as a string.
### Return value
A new iterable [`Segments`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Segmenter/segment/Segments) object containing the segments of the input string, using the segmenter's locale and granularity.
## Examples
```js
// Create a locale-specific word segmenter
const segmenter = new Intl.Segmenter("fr", { granularity: "word" });
// Use it to get an iterator over the segments of a string
const input = "Moi ? N'est-ce pas ?";
const segments = segmenter.segment(input);
// Use that for segmentation
for (const { segment, index, isWordLike } of segments) {
console.log(
"segment at code units [%d, %d]: «%s»%s",
index,
index + segment.length,
segment,
isWordLike ? " (word-like)" : "",
);
}
// segment at code units [0, 3]: «Moi» (word-like)
// segment at code units [3, 4]: « »
// segment at code units [4, 5]: «?»
// segment at code units [5, 6]: « »
// segment at code units [6, 11]: «N'est» (word-like)
// segment at code units [11, 12]: «-»
// segment at code units [12, 14]: «ce» (word-like)
// segment at code units [14, 15]: « »
// segment at code units [15, 18]: «pas» (word-like)
// segment at code units [18, 19]: « »
// segment at code units [19, 20]: «?»
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/segmenter/segment | data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/segmenter/segment/segments/index.md | ---
title: Segments
slug: Web/JavaScript/Reference/Global_Objects/Intl/Segmenter/segment/Segments
page-type: javascript-class
browser-compat: javascript.builtins.Intl.Segments
---
{{JSRef}}
A **`Segments`** object is an iterable collection of the segments of a text string. It is returned by a call to the [`segment()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Segmenter/segment) method of an [`Intl.Segmenter`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Segmenter) object.
{{EmbedInteractiveExample("pages/js/segments-prototype-containing.html")}}
## Instance methods
- [`Segments.prototype.containing()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Segmenter/segment/Segments/containing)
- : Returns an object describing the segment in the original string that includes the code unit at a specified index.
- [`Segments.prototype[@@iterator]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Segmenter/segment/Segments/@@iterator)
- : Returns an iterator to iterate over the segments.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [`Intl.Segmenter`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Segmenter)
- [`Intl.Segmenter.prototype.segment()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Segmenter/segment)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/segmenter/segment/segments | data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/segmenter/segment/segments/containing/index.md | ---
title: Segments.prototype.containing()
slug: Web/JavaScript/Reference/Global_Objects/Intl/Segmenter/segment/Segments/containing
page-type: javascript-instance-method
browser-compat: javascript.builtins.Intl.Segments.containing
---
{{JSRef}}
The **`containing()`** method of [`Segments`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Segmenter/segment/Segments) instances returns an object describing the segment in the string that includes the code unit at the specified index.
{{EmbedInteractiveExample("pages/js/segments-prototype-containing.html")}}
## Syntax
```js-nolint
containing(codeUnitIndex)
```
### Parameters
- `codeUnitIndex` {{optional_inline}}
- : A number specifying the index of the code unit in the original input string. If the value is omitted, it defaults to `0`.
### Return value
An object describing the segment of the original string with the following properties, or `undefined` if the supplied index value is out of bounds.
- `segment`
- : A string containing the segment extracted from the original input string.
- `index`
- : The code unit index in the original input string at which the segment begins.
- `input`
- : The complete input string that was segmented.
- `isWordLike`
- : A boolean value only if `granularity` is `"word"`; otherwise, `undefined`. If `granularity` is `"word"`, then `isWordLike` is `true` when the segment is word-like (i.e., consists of letters/numbers/ideographs/etc.); otherwise, `false`.
## Examples
```js
// ┃0 1 2 3 4 5┃6┃7┃8┃9 ← code unit index
// ┃A l l o n s┃-┃y┃!┃ ← code unit
const input = "Allons-y!";
const segmenter = new Intl.Segmenter("fr", { granularity: "word" });
const segments = segmenter.segment(input);
let current = segments.containing();
// { index: 0, segment: "Allons", isWordLike: true }
current = segments.containing(4);
// { index: 0, segment: "Allons", isWordLike: true }
current = segments.containing(6);
// { index: 6, segment: "-", isWordLike: false }
current = segments.containing(current.index + current.segment.length);
// { index: 7, segment: "y", isWordLike: true }
current = segments.containing(current.index + current.segment.length);
// { index: 8, segment: "!", isWordLike: false }
current = segments.containing(current.index + current.segment.length);
// undefined
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [`Intl.Segmenter`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Segmenter)
- [`Intl.Segmenter.prototype.segment()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Segmenter/segment)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/segmenter/segment/segments | data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/segmenter/segment/segments/@@iterator/index.md | ---
title: Segments.prototype[@@iterator]()
slug: Web/JavaScript/Reference/Global_Objects/Intl/Segmenter/segment/Segments/@@iterator
page-type: javascript-instance-method
browser-compat: javascript.builtins.Intl.Segments.@@iterator
---
{{JSRef}}
The **`[@@iterator]()`** method of [`Segments`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Segmenter/segment/Segments) instances implements the [iterable protocol](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) and allows `Segments` objects to be consumed by most syntaxes expecting iterables, such as the [spread syntax](/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax) and {{jsxref("Statements/for...of", "for...of")}} loops. It returns a [segments iterator object](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator) that yields data about each segment.
{{EmbedInteractiveExample("pages/js/segments-prototype-@@iterator.html")}}
## Syntax
```js-nolint
segments[Symbol.iterator]()
```
### Parameters
None.
### Return value
A new [iterable iterator object](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator) that yields data about each segment. Each yielded object has the same properties as the object returned by the [`containing()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Segmenter/segment/Segments/containing) method.
## Examples
### Iteration using for...of loop
Note that you seldom need to call this method directly. The existence of the `@@iterator` method makes `Segments` objects [iterable](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol), and iterating syntaxes like the `for...of` loop automatically call this method to obtain the iterator to loop over.
```js
const segmenter = new Intl.Segmenter("zh-CN", { granularity: "word" });
const input = "你好,世界!我爱编程。";
for (const value of segmenter.segment(input)) {
console.log(value);
}
/*
{segment: '你好', index: 0, input: '你好,世界!我爱编程。', isWordLike: true}
{segment: ',', index: 2, input: '你好,世界!我爱编程。', isWordLike: false}
{segment: '世界', index: 3, input: '你好,世界!我爱编程。', isWordLike: true}
{segment: '!', index: 5, input: '你好,世界!我爱编程。', isWordLike: false}
{segment: '我', index: 6, input: '你好,世界!我爱编程。', isWordLike: true}
{segment: '爱', index: 7, input: '你好,世界!我爱编程。', isWordLike: true}
{segment: '编', index: 8, input: '你好,世界!我爱编程。', isWordLike: true}
{segment: '程', index: 9, input: '你好,世界!我爱编程。', isWordLike: true}
{segment: '。', index: 10, input: '你好,世界!我爱编程。', isWordLike: false}
*/
```
### Manually hand-rolling the iterator
You may still manually call the `next()` method of the returned iterator object to achieve maximum control over the iteration process.
```js
const segmenter = new Intl.Segmenter("fr", { granularity: "word" });
const input = "Moi ? N'est-ce pas ?";
const segments = segmenter.segment(input);
const iterator = segments[Symbol.iterator]();
let result = iterator.next();
while (!result.done) {
console.log(result.value);
result = iterator.next();
}
/*
{segment: 'Moi', index: 0, input: "Moi ? N'est-ce pas ?", isWordLike: true}
{segment: ' ', index: 3, input: "Moi ? N'est-ce pas ?", isWordLike: false}
{segment: '?', index: 4, input: "Moi ? N'est-ce pas ?", isWordLike: false}
{segment: ' ', index: 5, input: "Moi ? N'est-ce pas ?", isWordLike: false}
{segment: "N'est", index: 6, input: "Moi ? N'est-ce pas ?", isWordLike: true}
{segment: '-', index: 11, input: "Moi ? N'est-ce pas ?", isWordLike: false}
{segment: 'ce', index: 12, input: "Moi ? N'est-ce pas ?", isWordLike: true}
{segment: ' ', index: 14, input: "Moi ? N'est-ce pas ?", isWordLike: false}
{segment: 'pas', index: 15, input: "Moi ? N'est-ce pas ?", isWordLike: true}
{segment: ' ', index: 18, input: "Moi ? N'est-ce pas ?", isWordLike: false}
{segment: '?', index: 19, input: "Moi ? N'est-ce pas ?", isWordLike: false}
*/
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [`Intl.Segmenter`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Segmenter)
- [`Intl.Segmenter.prototype.segment()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Segmenter/segment)
- {{jsxref("Symbol.iterator")}}
- [Iteration protocols](/en-US/docs/Web/JavaScript/Reference/Iteration_protocols)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/segmenter | data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/segmenter/resolvedoptions/index.md | ---
title: Intl.Segmenter.prototype.resolvedOptions()
slug: Web/JavaScript/Reference/Global_Objects/Intl/Segmenter/resolvedOptions
page-type: javascript-instance-method
browser-compat: javascript.builtins.Intl.Segmenter.resolvedOptions
---
{{JSRef}}
The **`resolvedOptions()`** method of {{jsxref("Intl.Segmenter")}} instances returns a new object with properties reflecting the locale and granularity options computed during the initialization of this `Intl.Segmenter` object.
{{EmbedInteractiveExample("pages/js/intl-segmenter-prototype-resolvedoptions.html")}}
## Syntax
```js-nolint
resolvedOptions()
```
### Parameters
None.
### Return value
A new object with properties reflecting the locale and collation options computed
during the initialization of the given [`Intl.Segmenter`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Segmenter) object.
## Description
The resulting object has the following properties:
- `locale`
- : The BCP 47 language tag for the locale actually used. If any Unicode extension
values were requested in the input BCP 47 language tag that led to this locale,
the key-value pairs that were requested and are supported for this locale are
included in `locale`.
- `granularity`
- : The value provided for this property in the `options` argument or filled
in as the default.
## Examples
### Basic usage
```js
const spanishSegmenter = new Intl.Segmenter("es", { granularity: "sentence" });
const options = spanishSegmenter.resolvedOptions();
console.log(options.locale); // "es"
console.log(options.granularity); // "sentence"
```
### Default granularity
```js
const spanishSegmenter = new Intl.Segmenter("es");
const options = spanishSegmenter.resolvedOptions();
console.log(options.locale); // "es"
console.log(options.granularity); // "grapheme"
```
### Fallback locale
```js
const banSegmenter = new Intl.Segmenter("ban");
const options = banSegmenter.resolvedOptions();
console.log(options.locale);
// "fr" on a runtime where the Balinese locale
// is not supported and French is the default locale
console.log(options.granularity); // "grapheme"
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/segmenter | data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/segmenter/supportedlocalesof/index.md | ---
title: Intl.Segmenter.supportedLocalesOf()
slug: Web/JavaScript/Reference/Global_Objects/Intl/Segmenter/supportedLocalesOf
page-type: javascript-static-method
browser-compat: javascript.builtins.Intl.Segmenter.supportedLocalesOf
---
{{JSRef}}
The **`Intl.Segmenter.supportedLocalesOf()`** static method returns an array containing those of the provided locales that are supported in segmentation without having to fall back to the runtime's default locale.
{{EmbedInteractiveExample("pages/js/intl-segmenter-supportedlocalesof.html", "shorter")}}
## Syntax
```js-nolint
Intl.Segmenter.supportedLocalesOf(locales)
Intl.Segmenter.supportedLocalesOf(locales, options)
```
### Parameters
- `locales`
- : A string with a BCP 47 language tag, or an array of such strings. For the general form and interpretation of the `locales` argument, see [the parameter description on the `Intl` main page](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#locales_argument).
- `options` {{optional_inline}}
- : An object that may have the following property:
- `localeMatcher`
- : The locale matching algorithm to use. Possible values are `"lookup"` and `"best fit"`; the default is `"best fit"`. For information about this option, see the {{jsxref("Intl", "Intl", "#locale_identification_and_negotiation", 1)}} page.
### Return value
An array of strings representing a subset of the given locale tags that are supported in segmentation without having to fall back to the runtime's default locale.
## Examples
### Using supportedLocalesOf()
Assuming a runtime that supports Indonesian and German but not Balinese in segmentation, `supportedLocalesOf` returns the Indonesian and German language tags unchanged, even though `pinyin` collation is neither relevant to segmentation nor used with Indonesian, and a specialized German for Indonesia is unlikely to be supported. Note the specification of the `"lookup"` algorithm here — a `"best fit"` matcher might decide that Indonesian is an adequate match for Balinese since most Balinese speakers also understand Indonesian, and therefore return the Balinese language tag as well.
```js
const locales = ["ban", "id-u-co-pinyin", "de-ID"];
const options = { localeMatcher: "lookup" };
console.log(Intl.Segmenter.supportedLocalesOf(locales, options));
// ["id-u-co-pinyin", "de-ID"]
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Intl.Segmenter")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl | data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/durationformat/index.md | ---
title: Intl.DurationFormat
slug: Web/JavaScript/Reference/Global_Objects/Intl/DurationFormat
page-type: javascript-class
status:
- experimental
browser-compat: javascript.builtins.Intl.DurationFormat
---
{{JSRef}} {{SeeCompatTable}}
The **`Intl.DurationFormat`** object enables language-sensitive duration formatting.
## Constructor
- {{jsxref("Intl/DurationFormat/DurationFormat", "Intl.DurationFormat()")}} {{experimental_inline}}
- : Creates a new `Intl.DurationFormat` object.
## Static methods
- {{jsxref("Intl/DurationFormat/supportedLocalesOf", "Intl.DurationFormat.supportedLocalesOf()")}} {{experimental_inline}}
- : Returns an array containing those of the provided locales that are supported without having to fall back to the runtime's default locale.
## Instance properties
These properties are defined on `Intl.DurationFormat.prototype` and shared by all `Intl.DurationFormat` instances.
- {{jsxref("Object/constructor", "Intl.DurationFormat.prototype.constructor")}}
- : The constructor function that created the instance object. For `Intl.DurationFormat` instances, the initial value is the {{jsxref("Intl/DurationFormat/DurationFormat", "Intl.DurationFormat")}} constructor.
- `Intl.DurationFormat.prototype[@@toStringTag]`
- : The initial value of the [`@@toStringTag`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/toStringTag) property is the string `"Intl.DurationFormat"`. This property is used in {{jsxref("Object.prototype.toString()")}}.
## Instance methods
- {{jsxref("Intl/DurationFormat/format", "Intl.DurationFormat.prototype.format()")}} {{experimental_inline}}
- : Getter function that formats a duration according to the locale and formatting options of this `DurationFormat` object.
- {{jsxref("Intl/DurationFormat/formatToParts", "Intl.DurationFormat.prototype.formatToParts()")}} {{experimental_inline}}
- : Returns an {{jsxref("Array")}} of objects representing the formatted duration in parts.
- {{jsxref("Intl/DurationFormat/resolvedOptions", "Intl.DurationFormat.prototype.resolvedOptions()")}} {{experimental_inline}}
- : Returns a new object with properties reflecting the locale and formatting options computed during initialization of the object.
## Examples
### Using Intl.DurationFormat
The examples below show how to use the `Intl.DurationFormat` object to format a duration object with various locales and styles.
```js
const duration = {
hours: 1,
minutes: 46,
seconds: 40,
};
// With style set to "long" and locale "fr-FR"
new Intl.DurationFormat("fr-FR", { style: "long" }).format(duration);
// "1 heure, 46 minutes et 40 secondes"
// With style set to "short" and locale "en"
new Intl.DurationFormat("en", { style: "short" }).format(duration);
// "1 hr, 46 min and 40 sec"
// With style set to "narrow" and locale "pt"
new Intl.DurationFormat("pt", { style: "narrow" }).format(duration);
// "1h 46min 40s"
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Intl")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/durationformat | data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/durationformat/format/index.md | ---
title: Intl.DurationFormat.prototype.format()
slug: Web/JavaScript/Reference/Global_Objects/Intl/DurationFormat/format
page-type: javascript-instance-method
status:
- experimental
browser-compat: javascript.builtins.Intl.DurationFormat.format
---
{{JSRef}} {{SeeCompatTable}}
The **`format()`** method of {{jsxref("Intl.DurationFormat")}} instances formats a duration according to the locale and formatting options of this {{jsxref("Intl.DurationFormat")}} object.
## Syntax
```js-nolint
format(duration)
```
### Parameters
- `duration`
- : The duration object to be formatted. It should include some or all of the following properties: `months`, `weeks`, `days`, `hours`, `minutes`, `seconds`, `milliseconds`, `microseconds`, `nanoseconds`.
### Return value
A string representing the given `duration` formatted according to the locale and formatting options of this {{jsxref("Intl.DurationFormat")}} object.
## Examples
### Using format()
The following example shows how to create a Duration formatter using the English language.
```js
const duration = {
years: 1,
months: 2,
weeks: 3,
days: 3,
hours: 4,
minutes: 5,
seconds: 6,
milliseconds: 7,
microseconds: 8,
nanoseconds: 9,
};
// Without options, style defaults to "short"
new Intl.DurationFormat("en").format(duration);
// "1 yr, 2 mths, 3 wks, 3 days, 4 hr, 5 min, 6 sec, 7 ms, 8 μs, 9 ns"
// With style set to "long"
new Intl.DurationFormat("en", { style: "long" }).format(duration);
// "1 year, 2 months, 3 weeks, 3 days, 4 hours, 5 minutes, 6 seconds, 7 milliseconds, 8 microseconds, 9 nanoseconds"
// With style set to "narrow"
new Intl.DurationFormat("en", { style: "narrow" }).format(duration);
// "1y 2mo 3w 3d 4h 5m 6s 7ms 8μs 9ns"
```
### Using format() with different locales and styles
```js
const duration = {
hours: 1,
minutes: 46,
seconds: 40,
};
// With style set to "long" and locale "fr-FR"
new Intl.DurationFormat("fr-FR", { style: "long" }).format(duration);
// "1 heure, 46 minutes et 40 secondes"
// With style set to "short" and locale set to "en"
new Intl.DurationFormat("en", { style: "short" }).format(duration);
// "1 hr, 46 min and 40 sec"
// With style set to "short" and locale set to "pt"
new Intl.DurationFormat("pt", { style: "narrow" }).format(duration);
// "1h 46min 40s"
// With style set to "digital" and locale set to "en"
new Intl.DurationFormat("en", { style: "digital" }).format(duration);
// "1:46:40"
// With style set to "digital", locale set to "en", and hours set to "long"
new Intl.DurationFormat("en", { style: "digital", hours: "long" }).format(
duration,
);
// "1 hour, 46:40"
```
### Using format() with the fractionalDigits option
```js
const duration = {
hours: 11,
minutes: 30,
seconds: 12,
milliseconds: 345,
microseconds: 600,
};
new Intl.DurationFormat("en", { style: "digital" }).format(duration);
// "11:30:12.3456"
new Intl.DurationFormat("en", { style: "digital", fractionalDigits: 5 }).format(
duration,
);
// "11:30:12.34560"
new Intl.DurationFormat("en", { style: "digital", fractionalDigits: 3 }).format(
duration,
);
// "11:30:12.346"
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Intl.DurationFormat")}}
- {{jsxref("Intl.supportedValuesOf()")}}
- {{jsxref("Intl")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/durationformat | data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/durationformat/durationformat/index.md | ---
title: Intl.DurationFormat() constructor
slug: Web/JavaScript/Reference/Global_Objects/Intl/DurationFormat/DurationFormat
page-type: javascript-constructor
status:
- experimental
browser-compat: javascript.builtins.Intl.DurationFormat.DurationFormat
---
{{JSRef}} {{SeeCompatTable}}
The **`Intl.DurationFormat()`** constructor creates {{jsxref("Intl.DurationFormat")}} objects.
## Syntax
```js-nolint
new Intl.DurationFormat()
new Intl.DurationFormat(locales)
new Intl.DurationFormat(locales, options)
```
> **Note:** `Intl.DurationFormat()` can only be constructed with [`new`](/en-US/docs/Web/JavaScript/Reference/Operators/new). Attempting to call it without `new` throws a {{jsxref("TypeError")}}.
### Parameters
- `locales` {{optional_inline}}
- : A string with a BCP 47 language tag or an {{jsxref("Intl.Locale")}} instance, or an array of such locale identifiers. For the general form and interpretation of the `locales` argument, see [the parameter description on the `Intl` main page](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#locales_argument).
The following Unicode extension key is allowed:
- `nu`
- : See [`numberingSystem`](#numberingsystem).
This key can also be set with `options` (as listed below). When both are set, the `options` property takes precedence.
- `options` {{optional_inline}}
- : An object containing the following properties, in the order they are retrieved (all of them are optional):
- `localeMatcher`
- : The locale matching algorithm to use. Possible values are `"lookup"` and `"best fit"`; the default is `"best fit"`. For information about this option, see [Locale identification and negotiation](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#locale_identification_and_negotiation).
- `numberingSystem`
- : The numbering system to use for number formatting, such as `"arab"`, `"hans"`, `"mathsans"`, and so on. For a list of supported numbering system types, see [`Intl.Locale.prototype.getNumberingSystems()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Locale/getNumberingSystems#supported_numbering_system_types). This option can also be set through the `nu` Unicode extension key; if both are provided, this `options` property takes precedence.
- `style`
- : The style of the formatted duration. Possible values are:
- `"long"`
- : E.g., 1 hour and 50 minutes
- `"short"` (default)
- : E.g., 1 hr, 50 min
- `"narrow"`
- : E.g., 1h 50m
- `"digital"`
- : E.g., 1:50:00
- `years`
- : The style of the formatted years. Possible values are `"long"`, `"short"`, and `"narrow"`; the default is `options.style` if it's not `"digital"`, and `"short"` otherwise.
- `yearsDisplay`
- : Whether to always display years, or only if nonzero. Possible values are `"always"` and `"auto"`; the default is `"auto"` if `years` is unspecified, and `"always"` otherwise.
- `months`
- : The style of the formatted months. Possible values are `"long"`, `"short"`, and `"narrow"`; the default is `options.style` if it's not `"digital"`, and `"short"` otherwise.
- `monthsDisplay`
- : Whether to always display months, or only if nonzero. Possible values are `"always"` and `"auto"`; the default is `"auto"` if `months` is unspecified, and `"always"` otherwise.
- `weeks`
- : The style of the formatted weeks. Possible values are `"long"`, `"short"`, and `"narrow"`; the default is `options.style` if it's not `"digital"`, and `"short"` otherwise.
- `weeksDisplay`
- : Whether to always display weeks, or only if nonzero. Possible values are `"always"` and `"auto"`; the default is `"auto"` if `weeks` is unspecified, and `"always"` otherwise.
- `days`
- : The style of the formatted days. Possible values are `"long"`, `"short"`, and `"narrow"`; the default is `options.style` if it's not `"digital"`, and `"short"` otherwise.
- `daysDisplay`
- : Whether to always display days, or only if nonzero. Possible values are `"always"` and `"auto"`; the default is `"auto"` if `days` is unspecified, and `"always"` otherwise.
- `hours`
- : The style of the formatted hours. Possible values are `"long"`, `"short"`, `"narrow"`, `"numeric"`, and `"2-digit"`; the default is `options.style` if it's not `"digital"`, and `"numeric"` otherwise.
- `hoursDisplay`
- : Whether to always display hours, or only if nonzero. Possible values are `"always"` and `"auto"`; the default is `"auto"` if `hours` is unspecified and `options.style` is not `"digital"`, and `"always"` otherwise.
- `minutes`
- : The style of the formatted minutes.
- If `hours` is `"numeric"` or `"2-digit"`, possible values are `"numeric"` and `"2-digit"`, and `"numeric"` is normalized to `"2-digit"`; the default is `"numeric"`.
- Otherwise, possible values are `"long"`, `"short"`, `"narrow"`, `"numeric"`, and `"2-digit"`; the default is `options.style` if it's not `"digital"`, and `"numeric"` otherwise.
- `minutesDisplay`
- : Whether to always display minutes, or only if nonzero. Possible values are `"always"` and `"auto"`; the default is `"auto"` if `minutes` is unspecified and `options.style` is not `"digital"`, and `"always"` otherwise.
- `seconds`
- : The style of the formatted seconds.
- If `minutes` is `"numeric"` or `"2-digit"`, possible values are `"numeric"` and `"2-digit"`, and `"numeric"` is normalized to `"2-digit"`; the default is `"numeric"`.
- Otherwise, possible values are `"long"`, `"short"`, `"narrow"`, `"numeric"`, and `"2-digit"`; the default is `options.style` if it's not `"digital"`, and `"numeric"` otherwise.
- `secondsDisplay`
- : Whether to always display seconds, or only if nonzero. Possible values are `"always"` and `"auto"`; the default is `"auto"` if `seconds` is unspecified and `options.style` is not `"digital"`, and `"always"` otherwise.
- `milliseconds`
- : The style of the formatted milliseconds.
- If `seconds` is `"numeric"` or `"2-digit"`, the only possible value is `"numeric"`; the default is `"numeric"`.
- Otherwise, possible values are `"long"`, `"short"`, `"narrow"`, and `"numeric"`; the default is `options.style` if it's not `"digital"`, and `"numeric"` otherwise.
- `millisecondsDisplay`
- : Whether to always display milliseconds, or only if nonzero.
- If `seconds` is `"numeric"` or `"2-digit"`, the only possible value is `"auto"`; the default is only `"auto"` when `milliseconds` is unspecified.
- Otherwise, possible values are `"always"` and `"auto"`; the default is `"auto"` if `milliseconds` is unspecified, and `"always"` otherwise.
- `microseconds`
- : The style of the formatted microseconds.
- If `milliseconds` is `"numeric"`, the only possible value is `"numeric"`; the default is `"numeric"`.
- Otherwise, possible values are `"long"`, `"short"`, `"narrow"`, and `"numeric"`; the default is `options.style` if it's not `"digital"`, and `"numeric"` otherwise.
- `microsecondsDisplay`
- : Whether to always display microseconds, or only if nonzero.
- If `milliseconds` is `"numeric"`, the only possible value is `"auto"`; the default is only `"auto"` when `microseconds` is unspecified.
- Otherwise, possible values are `"always"` and `"auto"`; the default is `"auto"` if `microseconds` is unspecified, and `"always"` otherwise.
- `nanoseconds`
- : The style of the formatted nanoseconds.
- If `microseconds` is `"numeric"`, the only possible value is `"numeric"`; the default is `"numeric"`.
- Otherwise, possible values are `"long"`, `"short"`, `"narrow"`, and `"numeric"`; the default is `options.style` if it's not `"digital"`, and `"numeric"` otherwise.
- `nanosecondsDisplay`
- : Whether to always display nanoseconds, or only if nonzero.
- If `microseconds` is `"numeric"`, the only possible value is `"auto"`; the default is only `"auto"` when `nanoseconds` is unspecified.
- Otherwise, possible values are `"always"` and `"auto"`; the default is `"auto"` if `nanoseconds` is unspecified, and `"always"` otherwise.
- `fractionalDigits`
- : Number of how many fractional second digits to display in the output. Possible values are from `0` to `9`; the default is `undefined` (include as many fractional digits as necessary).
### Exceptions
- {{jsxref("RangeError")}}
- : Thrown if `locales` or `options` contain invalid values.
## Description
For each time segment, an {{jsxref("Intl.NumberFormat")}} object is constructed under the hood. It uses the following options (see {{jsxref("Intl/NumberFormat/NumberFormat", "Intl.NumberFormat()")}} for details):
- `numberingSystem`: the value of `options.numberingSystem`
When `milliseconds`, `microseconds`, or `nanoseconds` uses the `"numeric"` style, the following options are also used:
- `minimumFractionDigits`: `0` when `options.fractionalDigits` is `undefined`, `options.fractionalDigits` otherwise
- `maximumFractionDigits`: `9` when `options.fractionalDigits` is `undefined`, `options.fractionalDigits` otherwise
- `roundingMode`: `"trunc"`
When the time segment uses the `"2-digit"` style, the following options are also used:
- `minimumIntegerDigits`: `2`
When the time segment uses the `"long"`, `"short"`, or `"narrow"` style, the following options are also used:
- `style`: `"unit"` when `"long"`, `"short"`, or `"narrow"` is specified, `undefined` otherwise
- `unit`: the currently formatted unit (`"years"`, `"days"`, `"nanoseconds"`, etc.)
- `unitDisplay`: the value of the time segment style (`"long"`, `"short"`, or `"narrow"`)
## Examples
### Using the Intl.DurationFormat() constructor
```js
const duration = {
hours: 2,
minutes: 20,
seconds: 35,
};
console.log(new Intl.DurationFormat("pt", { style: "long" }).format(duration));
// "2 horas, 20 minutos e 35 segundos"
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Intl.DurationFormat")}}
- {{jsxref("Intl.supportedValuesOf()")}}
- {{jsxref("Intl")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/durationformat | data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/durationformat/resolvedoptions/index.md | ---
title: Intl.DurationFormat.prototype.resolvedOptions()
slug: Web/JavaScript/Reference/Global_Objects/Intl/DurationFormat/resolvedOptions
page-type: javascript-instance-method
status:
- experimental
browser-compat: javascript.builtins.Intl.DurationFormat.resolvedOptions
---
{{JSRef}} {{SeeCompatTable}}
The **`resolvedOptions()`** method of {{jsxref("Intl.DurationFormat")}} instances returns a new object with properties reflecting the locale and date and time formatting options computed during initialization of this {{jsxref("Intl.DurationFormat")}} object.
## Syntax
```js-nolint
resolvedOptions()
```
### Parameters
None.
### Return value
A new object with properties reflecting the locale and date and time formatting options computed during the initialization of the given {{jsxref("Intl.DateTimeFormat")}} object.
## Description
The resulting object has the following properties:
- `locale`
- : The [BCP 47 language tag](https://datatracker.ietf.org/doc/html/rfc5646) for the locale used. If any Unicode extension values were requested in the input BCP 47 language tag that led to this locale, the key-value pairs that were requested and are supported for this locale are included in `locale`.
- `style`
- : One of the strings `"long"`, `"short"`, `"narrow"`, or `"digital"` identifying the duration formatting style used.
- `years`
- : One of the strings `"long"`, `"short"`, or `"narrow"` identifying the formatting style used for the `years` field.
- `yearsDisplay`
- : One of the strings `"auto"` or `"always"` identifying when to display the `years` field.
- `months`
- : One of the strings `"long"`, `"short"`, `and "narrow"` identifying the formatting style used for the `months` field.
- `monthsDisplay`
- : One of the strings `"auto"` or `"always"` identifying when to display the `months` field.
- `weeks`
- : One of the strings `"long"`, `"short"`, `and "narrow"` identifying the formatting style used for the `weeks` field.
- `weeksDisplay`
- : One of the strings `"auto"` or `"always"` identifying when to display the `weeks` field.
- `days`
- : One of the strings `"long"`, `"short"`, and `"narrow"` identifying the formatting style used for the `days` field.
- `daysDisplay`
- : One of the strings `"auto"` or `"always"` identifying when to display the `days` field.
- `hours`
- : One of the strings `"long"`, `"short"`, `"narrow"`, `"2-digit"`, or `"numeric"` identifying the formatting style used for the `hours` field.
- `hoursDisplay`
- : One of the strings `"auto"` or `"always"` identifying when to display the `hours` field.
- `minutes`
- : One of the strings `"long"`, `"short"`, `"narrow"`, `"2-digit"`, or `"numeric"` identifying the formatting style used for the `minutes` field.
- `minutesDisplay`
- : One of the strings `"auto"` or `"always"` identifying when to display the `minutes` field.
- `seconds`
- : One of the strings `"long"`, `"short"`, `"narrow"`, `"2-digit"`, or `"numeric"` identifying the formatting style used for the `seconds` field.
- `secondsDisplay`
- : One of the strings `"auto"` or `"always"` identifying when to display the `seconds` field.
- `milliseconds`
- : One of the strings `"long"`, `"short"`, `"narrow"`, or `"numeric"` identifying the formatting style used for the `milliseconds` field.
- `millisecondsDisplay`
- : One of the strings `"auto"` or `"always"` identifying when to display the `millisecondsDisplay` field.
- `microseconds`
- : One of the strings `"long"`, `"short"`, `"narrow"`, or `"numeric"` identifying the formatting style used for the `microseconds` field.
- `microsecondsDisplay`
- : One of the strings `"auto"` or `"always"` identifying when to display the `microsecondsDisplay` field.
- `nanoseconds`
- : One of the strings `"long"`, `"short"`, `"narrow"`, or `"numeric"` identifying the formatting style used for the `nanoseconds` field.
- `nanosecondsDisplay`
- : One of the strings `"auto"` or `"always"` identifying when to display the `nanosecondsDisplay` field.
- `fractionalDigits`
- : A number, identifying the number of fractional digits used with numeric styles.
- `numberingSystem`
- : The value provided for this property in the options argument, if present, or the value requested using the Unicode extension key `nu` or filled in as a default.
## Examples
### Using the resolvedOptions method
```js
const duration = new Intl.DurationFormat("en");
const usedOptions = duration.resolvedOptions();
usedOptions.locale; // "en"
usedOptions.numberingSystem; // "latn"
usedOptions.years; // "long"
usedOptions.yearsDisplay; // "auto"
usedOptions.style; // "long"
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Intl.DurationFormat")}}
- {{jsxref("Intl.supportedValuesOf()")}}
- {{jsxref("Intl")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/durationformat | data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/durationformat/formattoparts/index.md | ---
title: Intl.DurationFormat.prototype.formatToParts()
slug: Web/JavaScript/Reference/Global_Objects/Intl/DurationFormat/formatToParts
page-type: javascript-instance-method
status:
- experimental
browser-compat: javascript.builtins.Intl.DurationFormat.formatToParts
---
{{JSRef}} {{SeeCompatTable}}
The **`formatToParts()`** method of {{jsxref("Intl.DurationFormat")}} instances allows locale-aware formatting of strings produced by {{jsxref("Intl.DurationFormat")}} formatters.
## Syntax
```js-nolint
formatToParts(duration)
```
### Parameters
- `duration` {{optional_inline}}
- : The duration object to be formatted. It should include some or all of the following properties: `"months"`, `"weeks"`, `"days"`, `"hours"`, `"minutes"`, `"seconds"`, `"milliseconds"`, `"microseconds"`, `"nanoseconds"`.
### Return value
An {{jsxref("Array")}} of objects containing the formatted duration in parts.
## Description
The `formatToParts()` method is useful for custom formatting of duration objects. It returns an {{jsxref("Array")}} of objects containing the locale-specific tokens from which it possible to build custom strings while preserving the locale-specific parts. The structure the `formatToParts()` method returns, looks like this:
```js
[
{ type: "integer", value: "7", unit: "hour" },
{ type: "literal", value: " ", unit: "hour" },
{ type: "unit", value: "hr", unit: "hour" },
{ type: "literal", value: ", " },
{ type: "integer", value: "8", unit: "minute" },
{ type: "literal", value: " ", unit: "minute" },
{ type: "unit", value: "min", unit: "minute" },
];
```
## Examples
The `formatToParts` method enables locale-aware formatting of strings produced by `DurationFormat` formatters by providing you the string in parts:
```js
const duration = {
hours: 7,
minutes: 8,
seconds: 9,
milliseconds: 123,
microseconds: 456,
nanoseconds: 789,
};
new Intl.DurationFormat("en", { style: "long" }).formatToParts(duration);
// Returned value:
[
{ type: "integer", value: "7", unit: "hour" },
{ type: "literal", value: " ", unit: "hour" },
{ type: "unit", value: "hours", unit: "hour" },
{ type: "literal", value: ", " },
{ type: "integer", value: "8", unit: "minute" },
{ type: "literal", value: " ", unit: "minute" },
{ type: "unit", value: "minutes", unit: "minute" },
{ type: "literal", value: ", " },
{ type: "integer", value: "9", unit: "second" },
{ type: "literal", value: " ", unit: "second" },
{ type: "unit", value: "seconds", unit: "second" },
{ type: "literal", value: ", " },
{ type: "integer", value: "123", unit: "millisecond" },
{ type: "literal", value: " ", unit: "millisecond" },
{ type: "unit", value: "milliseconds", unit: "millisecond" },
{ type: "literal", value: ", " },
{ type: "integer", value: "456", unit: "microsecond" },
{ type: "literal", value: " ", unit: "microsecond" },
{ type: "unit", value: "microseconds", unit: "microsecond" },
{ type: "literal", value: " and " },
{ type: "integer", value: "789", unit: "nanosecond" },
{ type: "literal", value: " ", unit: "nanosecond" },
{ type: "unit", value: "nanoseconds", unit: "nanosecond" },
];
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Intl.DurationFormat")}}
- {{jsxref("Intl.supportedValuesOf()")}}
- {{jsxref("Intl")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/durationformat | data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/durationformat/supportedlocalesof/index.md | ---
title: Intl.DurationFormat.supportedLocalesOf()
slug: Web/JavaScript/Reference/Global_Objects/Intl/DurationFormat/supportedLocalesOf
page-type: javascript-static-method
status:
- experimental
browser-compat: javascript.builtins.Intl.DurationFormat.supportedLocalesOf
---
{{JSRef}}{{SeeCompatTable}}
The **`Intl.DurationFormat.supportedLocalesOf()`** static method returns an array containing those of the provided locales that are supported in duration formatting without having to fall back to the runtime's default locale.
## Syntax
```js-nolint
Intl.DurationFormat.supportedLocalesOf(locales)
Intl.DurationFormat.supportedLocalesOf(locales, options)
```
### Parameters
- `locales`
- : A string with a BCP 47 language tag, or an array of such strings. For the general form and interpretation of the `locales` argument, see [the parameter description on the `Intl` main page](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#locales_argument).
- `options` {{optional_inline}}
- : An object that may have the following property:
- `localeMatcher`
- : The locale matching algorithm to use. Possible values are `"lookup"` and `"best fit"`; the default is `"best fit"`. For information about this option, see the {{jsxref("Intl", "Intl", "#locale_identification_and_negotiation", 1)}} page.
### Return value
An array of strings representing a subset of the given locale tags that are supported in duration formatting without having to fall back to the runtime's default locale.
## Examples
### Using supportedLocalesOf()
Assuming a runtime that supports Indonesian and German but not Balinese in duration formatting, `supportedLocalesOf` returns the Indonesian and German language tags unchanged, even though `pinyin` collation is neither relevant to duration formatting nor used with Indonesian, and a specialized German for Indonesia is unlikely to be supported. Note the specification of the `"lookup"` algorithm here — a `"best fit"` matcher might decide that Indonesian is an adequate match for Balinese since most Balinese speakers also understand Indonesian, and therefore return the Balinese language tag as well.
```js
const locales = ["ban", "id-u-co-pinyin", "de-ID"];
const options = { localeMatcher: "lookup" };
console.log(Intl.DurationFormat.supportedLocalesOf(locales, options));
// ["id-u-co-pinyin", "de-ID"]
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Intl.DurationFormat")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl | data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/displaynames/index.md | ---
title: Intl.DisplayNames
slug: Web/JavaScript/Reference/Global_Objects/Intl/DisplayNames
page-type: javascript-class
browser-compat: javascript.builtins.Intl.DisplayNames
---
{{JSRef}}
The **`Intl.DisplayNames`** object enables the consistent translation of language, region and script display names.
{{EmbedInteractiveExample("pages/js/intl-displaynames.html")}}
## Constructor
- {{jsxref("Intl/DisplayNames/DisplayNames", "Intl.DisplayNames()")}}
- : Creates a new `Intl.DisplayNames` object.
## Static methods
- {{jsxref("Intl/DisplayNames/supportedLocalesOf", "Intl.DisplayNames.supportedLocalesOf()")}}
- : Returns an array containing those of the provided locales that are supported without having to fall back to the runtime's default locale.
## Instance properties
These properties are defined on `Intl.DisplayNames.prototype` and shared by all `Intl.DisplayNames` instances.
- {{jsxref("Object/constructor", "Intl.DisplayNames.prototype.constructor")}}
- : The constructor function that created the instance object. For `Intl.DisplayNames` instances, the initial value is the {{jsxref("Intl/DisplayNames/DisplayNames", "Intl.DisplayNames")}} constructor.
- `Intl.DisplayNames.prototype[@@toStringTag]`
- : The initial value of the [`@@toStringTag`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/toStringTag) property is the string `"Intl.DisplayNames"`. This property is used in {{jsxref("Object.prototype.toString()")}}.
## Instance methods
- {{jsxref("Intl/DisplayNames/of", "Intl.DisplayNames.prototype.of()")}}
- : This method receives a `code` and returns a string based on the locale and options provided when instantiating `Intl.DisplayNames`.
- {{jsxref("Intl/DisplayNames/resolvedOptions", "Intl.DisplayNames.prototype.resolvedOptions()")}}
- : Returns a new object with properties reflecting the locale and formatting options computed during initialization of the object.
## Examples
### Region Code Display Names
To create an `Intl.DisplayNames` for a locale and get the display name for a region code.
```js
// Get display names of region in English
let regionNames = new Intl.DisplayNames(["en"], { type: "region" });
regionNames.of("419"); // "Latin America"
regionNames.of("BZ"); // "Belize"
regionNames.of("US"); // "United States"
regionNames.of("BA"); // "Bosnia & Herzegovina"
regionNames.of("MM"); // "Myanmar (Burma)"
// Get display names of region in Traditional Chinese
regionNames = new Intl.DisplayNames(["zh-Hant"], { type: "region" });
regionNames.of("419"); // "拉丁美洲"
regionNames.of("BZ"); // "貝里斯"
regionNames.of("US"); // "美國"
regionNames.of("BA"); // "波士尼亞與赫塞哥維納"
regionNames.of("MM"); // "緬甸"
```
### Language Display Names
To create an `Intl.DisplayNames` for a locale and get the display name for a language-script-region sequence.
```js
// Get display names of language in English
let languageNames = new Intl.DisplayNames(["en"], { type: "language" });
languageNames.of("fr"); // "French"
languageNames.of("de"); // "German"
languageNames.of("fr-CA"); // "Canadian French"
languageNames.of("zh-Hant"); // "Traditional Chinese"
languageNames.of("en-US"); // "American English"
languageNames.of("zh-TW"); // "Chinese (Taiwan)"]
// Get display names of language in Traditional Chinese
languageNames = new Intl.DisplayNames(["zh-Hant"], { type: "language" });
languageNames.of("fr"); // "法文"
languageNames.of("zh"); // "中文"
languageNames.of("de"); // "德文"
```
### Script Code Display Names
To create an `Intl.DisplayNames` for a locale and get the display name for a script code.
```js
// Get display names of script in English
let scriptNames = new Intl.DisplayNames(["en"], { type: "script" });
// Get script names
scriptNames.of("Latn"); // "Latin"
scriptNames.of("Arab"); // "Arabic"
scriptNames.of("Kana"); // "Katakana"
// Get display names of script in Traditional Chinese
scriptNames = new Intl.DisplayNames(["zh-Hant"], { type: "script" });
scriptNames.of("Latn"); // "拉丁文"
scriptNames.of("Arab"); // "阿拉伯文"
scriptNames.of("Kana"); // "片假名"
```
### Currency Code Display Names
To create an `Intl.DisplayNames` for a locale and get the display name for currency code.
```js
// Get display names of currency code in English
let currencyNames = new Intl.DisplayNames(["en"], { type: "currency" });
// Get currency names
currencyNames.of("USD"); // "US Dollar"
currencyNames.of("EUR"); // "Euro"
currencyNames.of("TWD"); // "New Taiwan Dollar"
currencyNames.of("CNY"); // "Chinese Yuan"
// Get display names of currency code in Traditional Chinese
currencyNames = new Intl.DisplayNames(["zh-Hant"], { type: "currency" });
currencyNames.of("USD"); // "美元"
currencyNames.of("EUR"); // "歐元"
currencyNames.of("TWD"); // "新台幣"
currencyNames.of("CNY"); // "人民幣"
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Intl")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/displaynames | data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/displaynames/displaynames/index.md | ---
title: Intl.DisplayNames() constructor
slug: Web/JavaScript/Reference/Global_Objects/Intl/DisplayNames/DisplayNames
page-type: javascript-constructor
browser-compat: javascript.builtins.Intl.DisplayNames.DisplayNames
---
{{JSRef}}
The **`Intl.DisplayNames()`** constructor creates {{jsxref("Intl.DisplayNames")}} objects.
{{EmbedInteractiveExample("pages/js/intl-displaynames.html")}}
## Syntax
```js-nolint
new Intl.DisplayNames(locales, options)
```
> **Note:** `Intl.DisplayNames()` can only be constructed with [`new`](/en-US/docs/Web/JavaScript/Reference/Operators/new). Attempting to call it without `new` throws a {{jsxref("TypeError")}}.
### Parameters
- `locales`
- : A string with a BCP 47 language tag or an {{jsxref("Intl.Locale")}} instance, or an array of such locale identifiers. For the general form and interpretation of the `locales` argument, see [the parameter description on the `Intl` main page](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#locales_argument).
- `options`
- : An object containing the following properties, in the order they are retrieved:
- `localeMatcher` {{optional_inline}}
- : The locale matching algorithm to use. Possible values are `"lookup"` and `"best fit"`; the default is `"best fit"`. For information about this option, see [Locale identification and negotiation](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#locale_identification_and_negotiation).
- `style` {{optional_inline}}
- : The formatting style to use. Possible values are `"narrow"`, `"short"`, and `"long"`; the default is `"long"`.
- `type`
- : The type of display names to return from [`of()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DisplayNames/of). Possible values are `"language"`, `"region"`, `"script"`, `"currency"`, `"calendar"`, and `"dateTimeField"`.
- `fallback` {{optional_inline}}
- : What to return from `of()` if the input is structurally valid but there's no matching display name. Possible values are:
- `"code"` (default)
- : Return the input code itself.
- `"none"`
- : Return `undefined`.
- `languageDisplay` {{optional_inline}}
- : How language names should be displayed. Only usable along with `type: "language"`. Possible values are:
- `"dialect"` (default)
- : Display special regional dialects using their own name. E.g. `"nl-BE"` will be displayed as `"Flemish"`.
- `"standard"`
- : Display all languages using standard format. E.g. `"nl-BE"` will be displayed as `"Dutch (Belgium)"`.
### Exceptions
- {{jsxref("TypeError")}}
- : Thrown if `options.type` is not provided.
- {{jsxref("RangeError")}}
- : Thrown if `locales` or `options` contain invalid values.
## Examples
### Basic usage
In basic use without specifying a locale, a formatted string in the default locale and
with default options is returned.
```js
console.log(new Intl.DisplayNames([], { type: "language" }).of("US"));
// 'us'
```
### Using type `dateTimeField`
Example using `dateTimeField` as a type option, will return the localized date time names strings.
```js
const dn = new Intl.DisplayNames("pt", { type: "dateTimeField" });
console.log(dn.of("era")); // 'era'
console.log(dn.of("year")); // 'ano'
console.log(dn.of("month")); // 'mês'
console.log(dn.of("quarter")); // 'trimestre'
console.log(dn.of("weekOfYear")); // 'semana'
console.log(dn.of("weekday")); // 'dia da semana'
console.log(dn.of("dayPeriod")); // 'AM/PM'
console.log(dn.of("day")); // 'dia'
console.log(dn.of("hour")); // 'hora'
console.log(dn.of("minute")); // 'minuto'
console.log(dn.of("second")); // 'segundo'
```
### Using type `calendar`
Example using `calendar` as a type option, will return the localized calendar names strings.
```js
const dn = new Intl.DisplayNames("en", { type: "calendar" });
console.log(dn.of("roc")); // 'Minguo Calendar'
console.log(dn.of("gregory")); // 'Gregorian Calendar'
console.log(dn.of("chinese")); // 'Chinese Calendar'
```
### Using type `language` with `languageDisplay`
Example using `language` as a type with `languageDisplay` options.
```js
// Using `dialect` option
const dnDialect = new Intl.DisplayNames("en", {
type: "language",
languageDisplay: "dialect",
});
console.log(dnDialect.of("en-GB")); // 'British English'
// Using `standard` option
const dnStd = new Intl.DisplayNames("en", {
type: "language",
languageDisplay: "standard",
});
console.log(dnStd.of("en-GB")); // 'English (United Kingdom)'
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Intl.DisplayNames")}}
- {{jsxref("Intl.supportedValuesOf()")}}
- {{jsxref("Intl")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/displaynames | data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/displaynames/resolvedoptions/index.md | ---
title: Intl.DisplayNames.prototype.resolvedOptions()
slug: Web/JavaScript/Reference/Global_Objects/Intl/DisplayNames/resolvedOptions
page-type: javascript-instance-method
browser-compat: javascript.builtins.Intl.DisplayNames.resolvedOptions
---
{{JSRef}}
The **`resolvedOptions()`** method of {{jsxref("Intl.DisplayNames")}} instances
returns a new object with properties reflecting the locale and style formatting
options computed during the construction of this `Intl.DisplayNames`
object.
## Syntax
```js-nolint
resolvedOptions()
```
### Parameters
None.
### Return value
An object with properties reflecting the locale and formatting options computed during
the construction of the given {{jsxref("Intl.DisplayNames")}} object.
## Description
The object returned by `resolvedOptions()` has the following properties:
- `locale`
- : The BCP 47 language tag for the locale actually used. If any Unicode extension
values were requested in the input BCP 47 language tag that led to this locale,
the key-value pairs that were requested and are supported for this locale are
included in `locale`.
- `style`
- : The value provided for this property in the `options` argument of the
constructor or the default value (`"long"`). Its value is either
`"long"`, `"short"`, or `"narrow"`.
- `type`
- : The value provided for this property in the `options` argument of the
constructor or the default value (`"language"`). Its value is either
`"language"`, `"region"`, `"script"`, or
`"currency"`.
- `fallback`
- : The value provided for this property in the options argument of the constructor or
the default value (`"code"`). Its value is either `"code"`
or `"none"`.
## Examples
### Using resolvedOptions
```js
const displayNames = new Intl.DisplayNames(["de-DE"], { type: "region" });
const usedOptions = displayNames.resolvedOptions();
console.log(usedOptions.locale); // "de-DE"
console.log(usedOptions.style); // "long"
console.log(usedOptions.type); // "region"
console.log(usedOptions.fallback); // "code"
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Intl.DisplayNames")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/displaynames | data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/displaynames/of/index.md | ---
title: Intl.DisplayNames.prototype.of()
slug: Web/JavaScript/Reference/Global_Objects/Intl/DisplayNames/of
page-type: javascript-instance-method
browser-compat: javascript.builtins.Intl.DisplayNames.of
---
{{JSRef}}
The **`of()`** method of {{jsxref("Intl.DisplayNames")}} instances receives a code and returns a string based on the locale and options provided when instantiating this `Intl.DisplayNames` object.
{{EmbedInteractiveExample("pages/js/intl-displaynames.html")}}
## Syntax
```js-nolint
of(code)
```
### Parameters
- `code`
- : The `code` to provide depends on the `type`:
- If the type is "region", `code` should be either an [two-letter ISO 3166 region code](https://www.iso.org/iso-3166-country-codes.html), or a [three-digit UN M49 geographic region](https://unstats.un.org/unsd/methodology/m49/). It is required to follow the [`unicode_region_subtag`](https://unicode.org/reports/tr35/#unicode_region_subtag) grammar.
- If the type is "script", `code` should be an [four-letter ISO 15924 script code](https://unicode.org/iso15924/iso15924-codes.html). It is required to follow the [`unicode_script_subtag`](https://unicode.org/reports/tr35/#unicode_script_subtag) grammar.
- If the type is "language", `code` should be a _languageCode_ \["-" _scriptCode_] \["-" _regionCode_ ] \*("-" _variant_ ) subsequence of the [`unicode_language_id`](https://unicode.org/reports/tr35/#Unicode_language_identifier) grammar. _languageCode_ is either a two-letter ISO 639-1 language code or a three-letter ISO 639-2 language code.
- If the type is "currency", `code` should be a [three-letter ISO 4217 currency code](https://www.iso.org/iso-4217-currency-codes.html). It is required to have exactly three alphabetic characters.
- If the type is "dateTimeField", `code` should be one of: `"era"`, `"year"`, `"quarter"`, `"month"`, `"weekOfYear"`, `"weekday"`, `"day"`, `"dayPeriod"`, `"hour"`, `"minute"`, `"second"`, `"timeZoneName"`.
- If the type is "calendar", `code` should be a [calendar key](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Locale/calendar). It is required to follow the `type` grammar of a [Unicode locale identifier](https://unicode.org/reports/tr35/#32-unicode-locale-identifier).
### Return value
A language-specific formatted string, or `undefined` if there's no data for the input and `fallback` is `"none"`.
> **Note:** `fallback` is only used if `code` is structurally valid. See [using fallback](#using_fallback).
### Exceptions
- {{jsxref("RangeError")}}
- : Thrown if `code` is not structurally valid for the given `type`.
## Examples
### Using the of method
```js
const regionNames = new Intl.DisplayNames("en", { type: "region" });
regionNames.of("419"); // "Latin America"
const languageNames = new Intl.DisplayNames("en", { type: "language" });
languageNames.of("fr"); // "French"
const currencyNames = new Intl.DisplayNames("en", { type: "currency" });
currencyNames.of("EUR"); // "Euro"
```
### Using fallback
When the `Intl.DisplayNames` is constructed with `fallback: "code"`, the `of()` method will return the `code` if the input looks structurally valid but there's no data for the input. If `fallback` is `"none"`, `undefined` is returned.
```js
console.log(
new Intl.DisplayNames("en", { type: "region", fallback: "code" }).of("ZL"),
); // "ZL"
console.log(
new Intl.DisplayNames("en", { type: "region", fallback: "none" }).of("ZL"),
); // undefined
```
However, this only applies if the `code` is structurally valid. For example, if `type` is `"region"` but `code` does not follow the `unicode_region_subtag` grammar (2 alphabetic characters or 3 numeric characters), a {{jsxref("RangeError")}} is directly thrown instead of using the fallback.
```js
console.log(
new Intl.DisplayNames("en", { type: "region", fallback: "code" }).of("ZLC"),
); // throws RangeError: invalid value "ZLC" for option region
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Intl.DisplayNames")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/displaynames | data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/displaynames/supportedlocalesof/index.md | ---
title: Intl.DisplayNames.supportedLocalesOf()
slug: Web/JavaScript/Reference/Global_Objects/Intl/DisplayNames/supportedLocalesOf
page-type: javascript-static-method
browser-compat: javascript.builtins.Intl.DisplayNames.supportedLocalesOf
---
{{JSRef}}
The **`Intl.DisplayNames.supportedLocalesOf()`** static method returns an array containing those of the provided locales that are supported in display names without having to fall back to the runtime's default locale.
## Syntax
```js-nolint
Intl.DisplayNames.supportedLocalesOf(locales)
Intl.DisplayNames.supportedLocalesOf(locales, options)
```
### Parameters
- `locales`
- : A string with a BCP 47 language tag, or an array of such strings. For the general form and interpretation of the `locales` argument, see [the parameter description on the `Intl` main page](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#locales_argument).
- `options` {{optional_inline}}
- : An object that may have the following property:
- `localeMatcher`
- : The locale matching algorithm to use. Possible values are `"lookup"` and `"best fit"`; the default is `"best fit"`. For information about this option, see the {{jsxref("Intl", "Intl", "#locale_identification_and_negotiation", 1)}} page.
### Return value
An array of strings representing a subset of the given locale tags that are supported in display names without having to fall back to the runtime's default locale.
## Examples
### Using supportedLocalesOf()
Assuming a runtime that supports Indonesian and German but not Balinese in display names, `supportedLocalesOf` returns the Indonesian and German language tags unchanged, even though `pinyin` collation is neither relevant to display names nor used with Indonesian, and a specialized German for Indonesia is unlikely to be supported. Note the specification of the `"lookup"` algorithm here — a `"best fit"` matcher might decide that Indonesian is an adequate match for Balinese since most Balinese speakers also understand Indonesian, and therefore return the Balinese language tag as well.
```js
const locales = ["ban", "id-u-co-pinyin", "de-ID"];
const options = { localeMatcher: "lookup" };
console.log(Intl.DisplayNames.supportedLocalesOf(locales, options));
// ["id-u-co-pinyin", "de-ID"]
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Intl.DisplayNames")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl | data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/supportedvaluesof/index.md | ---
title: Intl.supportedValuesOf()
slug: Web/JavaScript/Reference/Global_Objects/Intl/supportedValuesOf
page-type: javascript-static-method
browser-compat: javascript.builtins.Intl.supportedValuesOf
---
{{JSRef}}
The **`Intl.supportedValuesOf()`** static method returns an array containing the supported calendar, collation, currency, numbering systems, or unit values supported by the implementation.
Duplicates are omitted and the array is sorted in ascending lexicographical order (or more precisely, using {{jsxref("Array/sort", "Array.prototype.sort()")}} with an `undefined` compare function).
The method can be used to feature-test whether values are supported in a particular implementation and download a polyfill only if necessary.
It can also be used to build UIs that allow users to select their preferred localized values, for example when the UI is created from WebGL or server-side.
{{EmbedInteractiveExample("pages/js/intl-supportedvaluesof.html", "taller")}}
## Syntax
```js-nolint
Intl.supportedValuesOf(key)
```
### Parameters
- `key`
- : A key string indicating the category of values to be returned. This is one of: `"calendar"`, `"collation"`, `"currency"`, `"numberingSystem"`, `"timeZone"`, `"unit"`.
### Return value
A sorted array of unique string values indicating the values supported by the implementation for the given key.
### Exceptions
- {{jsxref("RangeError")}}
- : Thrown if an unsupported key was passed as a parameter.
## Examples
### Feature testing
You can check that the method is supported by comparing to `undefined`:
```js
if (typeof Intl.supportedValuesOf !== "undefined") {
// method is supported
}
```
### Get all values for key
To get the supported values for calendar you call the method with the key `"calendar"`.
You can then iterate through the returned array as shown below:
```js
Intl.supportedValuesOf("calendar").forEach((calendar) => {
// "buddhist", "chinese", "coptic", "dangi", etc.
});
```
> **Note:** The array returned for calendar values will always include the value "gregory" (gregorian).
The other values are all obtained in the same way:
```js
Intl.supportedValuesOf("collation").forEach((collation) => {
// "compat", "dict", "emoji", etc.
});
Intl.supportedValuesOf("currency").forEach((currency) => {
// "ADP", "AED", "AFA", "AFN", "ALK", "ALL", "AMD", etc.
});
Intl.supportedValuesOf("numberingSystem").forEach((numberingSystem) => {
// "adlm", "ahom", "arab", "arabext", "bali", etc.
});
Intl.supportedValuesOf("timeZone").forEach((timeZone) => {
// "Africa/Abidjan", "Africa/Accra", "Africa/Addis_Ababa", "Africa/Algiers", etc.
});
Intl.supportedValuesOf("unit").forEach((unit) => {
// "acre", "bit", "byte", "celsius", "centimeter", etc.
});
```
### Invalid key throws RangeError
```js
try {
Intl.supportedValuesOf("someInvalidKey");
} catch (err) {
//Error: RangeError: invalid key: "someInvalidKey"
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `Intl.supportedValuesOf` in FormatJS](https://github.com/formatjs/formatjs/tree/main/packages/intl-enumerator)
- {{jsxref("Intl")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl | data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/pluralrules/index.md | ---
title: Intl.PluralRules
slug: Web/JavaScript/Reference/Global_Objects/Intl/PluralRules
page-type: javascript-class
browser-compat: javascript.builtins.Intl.PluralRules
---
{{JSRef}}
The **`Intl.PluralRules`** object enables plural-sensitive formatting and plural-related language rules.
## Description
Languages use different patterns for expressing both plural numbers of items (cardinal numbers) and for expressing the order of items (ordinal numbers).
English has two forms for expressing cardinal numbers: one for the singular "item" (1 hour, 1 dog, 1 fish) and the other for zero or any other number of "items" (0 hours, 2 lemmings, 100000.5 fish), while Chinese has only one form, and Arabic has six!
Similarly, English has four forms for expressing ordinal numbers: "th", "st", "nd", "rd", giving the sequence: 0th, 1st, 2nd, 3rd, 4th, 5th, ..., 21st, 22nd, 23rd, 24th, 25th, and so on, while both Chinese and Arabic only have one form for ordinal numbers.
Given a particular language and set of formatting options, the methods [`Intl.PluralRules.prototype.select()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/PluralRules/select) and [`Intl.PluralRules.prototype.selectRange()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/PluralRules/selectRange) return a _tag_ that represents the plural form of a single or a range of numbers, cardinal or ordinal.
Code can use the returned tags to represent numbers appropriately for the given language.
The full set of tags that might be returned are: `zero`, `one`, `two`, `few`, `many`, and `other` (the "general" plural form, also used if the language only has one form).
As English only has two forms for cardinal numbers, the `select()` method returns only two tags: `"one"` for the singular case, and `"other"` for all other cardinal numbers.
This allows construction of sentences that make sense in English for each case, such as: "1 dog is happy; do you want to play with it?" and "10 dogs are happy; do you want to play with them?".
Creating appropriate sentences for each form depends on the language, and even in English may not be as simple as just adding "s" to a noun to make the plural form.
Using the example above, we see that the form may affect:
- **Nouns**: 1 dogs/2 dogs (but not "fish" or "sheep", which have the same singular and plural form).
- **Verbs**: 1 dog _is_ happy, 2 dogs _are_ happy
- **Pronouns** (and other referents): Do you want to play with _it_ / _them_.
Other languages have more forms, and choosing appropriate sentences can be even more complex.
`select()` can return any of four tags for ordinal numbers in English, representing each of the allowed forms: `one` for "st" numbers (1, 21, 31, ...), `two` for "nd" numbers (2, 22, 32, ...), `few` for "rd" numbers (3, 33, 43, ...), and `other` for "th" numbers (0, 4-20, etc.).
Again, the returned tags allow appropriate formatting of strings describing an ordinal number.
For more information about the rules and how they are used, see [Plural Rules](https://cldr.unicode.org/index/cldr-spec/plural-rules).
For a list of the rules and how they apply for different languages, see the [LDML Language Plural Rules](https://www.unicode.org/cldr/charts/43/supplemental/language_plural_rules.html).
## Constructor
- {{jsxref("Intl/PluralRules/PluralRules", "Intl.PluralRules()")}}
- : Creates a new `Intl.PluralRules` object.
## Static methods
- {{jsxref("Intl/PluralRules/supportedLocalesOf", "Intl.PluralRules.supportedLocalesOf()")}}
- : Returns an array containing those of the provided locales that are supported without having to fall back to the runtime's default locale.
## Instance properties
These properties are defined on `Intl.PluralRules.prototype` and shared by all `Intl.PluralRules` instances.
- {{jsxref("Object/constructor", "Intl.PluralRules.prototype.constructor")}}
- : The constructor function that created the instance object. For `Intl.PluralRules` instances, the initial value is the {{jsxref("Intl/PluralRules/PluralRules", "Intl.PluralRules")}} constructor.
- `Intl.PluralRules.prototype[@@toStringTag]`
- : The initial value of the [`@@toStringTag`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/toStringTag) property is the string `"Intl.PluralRules"`. This property is used in {{jsxref("Object.prototype.toString()")}}.
## Instance methods
- {{jsxref("Intl/PluralRules/resolvedOptions", "Intl.PluralRules.prototype.resolvedOptions()")}}
- : Returns a new object with properties reflecting the locale and collation options computed during initialization of the object.
- {{jsxref("Intl/PluralRules/select", "Intl.PluralRules.prototype.select()")}}
- : Returns a string indicating which plural rule to use for locale-aware formatting.
- {{jsxref("Intl/PluralRules/selectRange", "Intl.PluralRules.prototype.selectRange()")}}
- : This method receives two values and returns a string indicating which plural rule to use for locale-aware formatting.
## Examples
### Using locales
This example shows some of the variations in localized plural rules for cardinal numbers.
In order to get the format for the language used in the user interface of your application, make sure to specify that language (and possibly some fallback languages) using the [constructor `locales`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/PluralRules/PluralRules#locales) argument:
```js
// US English
const enCardinalRules = new Intl.PluralRules("en-US");
console.log(enCardinalRules.select(0)); // "other"
console.log(enCardinalRules.select(1)); // "one"
console.log(enCardinalRules.select(2)); // "other"
console.log(enCardinalRules.select(3)); // "other"
// Arabic
const arCardinalRules = new Intl.PluralRules("ar-EG");
console.log(arCardinalRules.select(0)); // "zero"
console.log(arCardinalRules.select(1)); // "one"
console.log(arCardinalRules.select(2)); // "two"
console.log(arCardinalRules.select(6)); // "few"
console.log(arCardinalRules.select(18)); // "many"
```
### Using options
The plural form of the specified number may also depend on [constructor `options`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/PluralRules/PluralRules#options), such as how the number is rounded, and whether it is cardinal or ordinal.
This example shows how you can set the type of rules to "ordinal", and how this affects the form for some numbers in US English.
```js
// US English - ordinal
const enOrdinalRules = new Intl.PluralRules("en-US", { type: "ordinal" });
console.log(enOrdinalRules.select(0)); // "other" (0th)
console.log(enOrdinalRules.select(1)); // "one" (1st)
console.log(enOrdinalRules.select(2)); // "two" (2nd)
console.log(enOrdinalRules.select(3)); // "few" (3rd)
console.log(enOrdinalRules.select(4)); // "other" (4th)
console.log(enOrdinalRules.select(21)); // "one" (21st)
```
### Formatting text using the returned tag
The code below extends the previous example, showing how you might use the returned tag for an ordinal number to format text in English.
```js
const enOrdinalRules = new Intl.PluralRules("en-US", { type: "ordinal" });
const suffixes = new Map([
["one", "st"],
["two", "nd"],
["few", "rd"],
["other", "th"],
]);
const formatOrdinals = (n) => {
const rule = enOrdinalRules.select(n);
const suffix = suffixes.get(rule);
return `${n}${suffix}`;
};
formatOrdinals(0); // '0th'
formatOrdinals(1); // '1st'
formatOrdinals(2); // '2nd'
formatOrdinals(3); // '3rd'
formatOrdinals(4); // '4th'
formatOrdinals(11); // '11th'
formatOrdinals(21); // '21st'
formatOrdinals(42); // '42nd'
formatOrdinals(103); // '103rd'
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `Intl.PluralRules` in FormatJS](https://formatjs.io/docs/polyfills/intl-pluralrules/)
- {{jsxref("Intl")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/pluralrules | data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/pluralrules/resolvedoptions/index.md | ---
title: Intl.PluralRules.prototype.resolvedOptions()
slug: Web/JavaScript/Reference/Global_Objects/Intl/PluralRules/resolvedOptions
page-type: javascript-instance-method
browser-compat: javascript.builtins.Intl.PluralRules.resolvedOptions
---
{{JSRef}}
The **`resolvedOptions()`** method of {{jsxref("Intl.PluralRules")}} instances returns a new object with properties reflecting the locale and plural formatting options computed during initialization of this `Intl.PluralRules` object.
{{EmbedInteractiveExample("pages/js/intl-pluralrules-prototype-resolvedoptions.html")}}
## Syntax
```js-nolint
resolvedOptions()
```
### Parameters
None.
### Return value
A new object with properties reflecting the locale and plural formatting options computed during the initialization of the given {{jsxref("Intl.PluralRules")}} object.
The object has the following properties:
- `locale`
- : The BCP 47 language tag for the locale actually used. If any Unicode extension values were requested in the input BCP 47 language tag that led to this locale, the key-value pairs that were requested and are supported for this locale are included in `locale`.
- `pluralCategories`
- : An {{jsxref("Array")}} of plural categories used by the given locale, selected from the list `"zero"`, `"one"`, `"two"`, `"few"`, `"many"` and `"other"`.
- `type`
- : The type used (`cardinal` or `ordinal`).
- `roundingMode` {{experimental_inline}}
- : The rounding mode.
This is the value provided for the [`options.roundingMode`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/PluralRules/PluralRules#roundingmode) argument in the constructor, or the default value: `halfExpand`.
- `roundingPriority` {{experimental_inline}}
- : The priority for resolving rounding conflicts if both "FractionDigits" and "SignificantDigits" are specified.
This is the value provided for the [`options.roundingPriority`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/PluralRules/PluralRules#roundingpriority) argument in the constructor, or the default value: `auto`.
- `roundingIncrement` {{experimental_inline}}
- : The rounding-increment precision (the increment used when rounding numbers).
This is the value specified in the [`options.roundingIncrement`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/PluralRules/PluralRules#roundingincrement) argument in the constructor.
- `trailingZeroDisplay` {{experimental_inline}}
- : The strategy for displaying trailing zeros on whole numbers.
This is the value specified in the [`options.trailingZeroDisplay`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/PluralRules/PluralRules#trailingzerodisplay) argument in the constructor, or the default value: `"auto"`.
Only one of the following two groups of properties is included:
- `minimumIntegerDigits`, `minimumFractionDigits`, `maximumFractionDigits`
- : The values provided for these properties in the `options` argument or filled in as defaults.
These properties are present only if neither `minimumSignificantDigits` nor `maximumSignificantDigits` was provided in the `options` argument.
- `minimumSignificantDigits`, `maximumSignificantDigits`
- : The values provided for these properties in the `options` argument or filled in as defaults.
These properties are present only if at least one of them was provided in the `options` argument.
## Examples
### Using the resolvedOptions() method
The code below shows the construction of a `PluralRules` object, followed by logging of each of the resolved options.
```js
// Create a PluralRules instance
const de = new Intl.PluralRules("de-DE", {
maximumSignificantDigits: 2,
trailingZeroDisplay: "auto",
});
// Resolve the options
const usedOptions = de.resolvedOptions();
console.log(usedOptions.locale); // "de-DE"
console.log(usedOptions.pluralCategories); // Array ["one", "other"]
console.log(usedOptions.type); // "cardinal"
console.log(usedOptions.minimumIntegerDigits); // 1
console.log(usedOptions.minimumFractionDigits); // undefined (maximumSignificantDigits is set)
console.log(usedOptions.maximumFractionDigits); //undefined (maximumSignificantDigits is set)
console.log(usedOptions.minimumSignificantDigits); // 1
console.log(usedOptions.maximumSignificantDigits); //2
console.log(usedOptions.roundingIncrement); // 1
console.log(usedOptions.roundingMode); // "halfExpand"
console.log(usedOptions.roundingPriority); // "auto"
console.log(usedOptions.trailingZeroDisplay); // "auto"
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Intl.PluralRules")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/pluralrules | data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/pluralrules/select/index.md | ---
title: Intl.PluralRules.prototype.select()
slug: Web/JavaScript/Reference/Global_Objects/Intl/PluralRules/select
page-type: javascript-instance-method
browser-compat: javascript.builtins.Intl.PluralRules.select
---
{{JSRef}}
The **`select()`** method of {{jsxref("Intl.PluralRules")}} instances returns a string indicating which plural rule to use for locale-aware formatting of a number.
{{EmbedInteractiveExample("pages/js/intl-pluralrules-prototype-select.html")}}
## Syntax
```js-nolint
select(number)
```
### Parameters
- `number`
- : The number to get a plural rule for.
### Return value
A string representing the pluralization category of the `number`.
This can be one of `zero`, `one`, `two`, `few`, `many`, or `other`.
## Description
This function selects a pluralization category according to the locale and formatting options of an {{jsxref("Intl.PluralRules")}} object.
These options are set in the [`Intl.PluralRules()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/PluralRules/PluralRules) constructor.
## Examples
### Using select()
First, create an `Intl.PluralRules` object, passing the appropriate `locales` and `options` parameters.
Here we create a plural rules object for Arabic in the Egyptian dialect.
Because the `type` is not specified the rules object will provide formatting for cardinal numbers (the default).
```js
const pr = new Intl.PluralRules("ar-EG");
```
Then call `select()` on the rules object, specifying the number for which the plural form is required.
Note that Arabic has 5 forms for cardinal numbers, as shown.
```js
pr.select(0); // 'zero'
pr.select(1); // 'one'
pr.select(2); // 'two'
pr.select(6); // 'few'
pr.select(18); // 'many'
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Intl.PluralRules")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/pluralrules | data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/pluralrules/selectrange/index.md | ---
title: Intl.PluralRules.prototype.selectRange()
slug: Web/JavaScript/Reference/Global_Objects/Intl/PluralRules/selectRange
page-type: javascript-instance-method
browser-compat: javascript.builtins.Intl.PluralRules.selectRange
---
{{JSRef}}
The **`selectRange()`** method of {{jsxref("Intl.PluralRules")}} instances receives two values and returns a string indicating which plural rule to use for locale-aware formatting of the indicated range.
## Syntax
```js-nolint
selectRange(startRange, endRange)
```
### Parameters
- `startRange`
- : A number representing the start of the range.
- `endRange`
- : A number representing the end of the range.
### Return value
A string representing the pluralization category of the specified range.
This can be one of `zero`, `one`, `two`, `few`, `many` or `other`, that are relevant for the locale whose localization is specified in [LDML Language Plural Rules](https://www.unicode.org/cldr/charts/43/supplemental/language_plural_rules.html).
## Description
This function selects a pluralization category according to the locale and formatting options of an {{jsxref("Intl.PluralRules")}} object.
Conceptually the behavior is the same as getting plural rules for a single cardinal or ordinal number.
Languages have one or more forms for describing ranges, and this method returns the appropriate form given the supplied locale and formatting options.
In English there is only one plural form, such as "1–10 apples", and the method will return `other`.
Other languages can have many forms.
## Examples
### Using selectRange()
```js
new Intl.PluralRules("sl").selectRange(102, 201); // 'few'
new Intl.PluralRules("pt").selectRange(102, 102); // 'other'
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Intl.PluralRules")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/pluralrules | data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/pluralrules/pluralrules/index.md | ---
title: Intl.PluralRules() constructor
slug: Web/JavaScript/Reference/Global_Objects/Intl/PluralRules/PluralRules
page-type: javascript-constructor
browser-compat: javascript.builtins.Intl.PluralRules.PluralRules
---
{{JSRef}}
The **`Intl.PluralRules()`** constructor creates {{jsxref("Intl.PluralRules")}} objects.
## Syntax
```js-nolint
new Intl.PluralRules()
new Intl.PluralRules(locales)
new Intl.PluralRules(locales, options)
```
> **Note:** `Intl.PluralRules()` can only be constructed with [`new`](/en-US/docs/Web/JavaScript/Reference/Operators/new). Attempting to call it without `new` throws a {{jsxref("TypeError")}}.
### Parameters
- `locales` {{optional_inline}}
- : A string with a BCP 47 language tag or an {{jsxref("Intl.Locale")}} instance, or an array of such locale identifiers. For the general form and interpretation of the `locales` argument, see [the parameter description on the `Intl` main page](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#locales_argument).
- `options` {{optional_inline}}
- : An object containing the following properties, in the order they are retrieved (all of them are optional):
- `localeMatcher`
- : The locale matching algorithm to use. Possible values are `"lookup"` and `"best fit"`; the default is `"best fit"`. For information about this option, see [Locale identification and negotiation](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#locale_identification_and_negotiation).
- `type`
- : The type to use. Possible values are:
- `"cardinal"` (default)
- : For cardinal numbers (referring to the quantity of things).
- `"ordinal"`
- : For ordinal number (referring to the ordering or ranking of things, e.g. "1st", "2nd", "3rd" in English).
`Intl.PluralRules` also supports the `Intl.NumberFormat()` [digit options](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#digit_options) (see `Intl.NumberFormat()` for details):
- `minimumIntegerDigits`
- `minimumFractionDigits`
- `maximumFractionDigits`
- `minimumSignificantDigits`
- `maximumSignificantDigits`
- `roundingPriority`
- `roundingIncrement`
- `roundingMode`
These options are interpreted as if the `notation` option from `Intl.NumberFormat` is `"standard"` and `style` is `"decimal"`.
### Exceptions
- {{jsxref("RangeError")}}
- : Thrown if `locales` or `options` contain invalid values.
## Examples
### Basic usage
In basic use without specifying a locale, a formatted string in the default locale and with default options is returned.
This is useful to distinguish between singular and plural forms, e.g. "dog" and "dogs".
```js
const pr = new Intl.PluralRules();
pr.select(0); // 'other' if in US English locale
pr.select(1); // 'one' if in US English locale
pr.select(2); // 'other' if in US English locale
```
### Using options
The results can be customized using the `options` argument, which has one property called `type` which you can set to `ordinal`. This is useful to figure out the ordinal indicator, e.g. "1st", "2nd", "3rd", "4th", "42nd",
and so forth.
```js
const pr = new Intl.PluralRules("en-US", { type: "ordinal" });
const suffixes = new Map([
["one", "st"],
["two", "nd"],
["few", "rd"],
["other", "th"],
]);
const formatOrdinals = (n) => {
const rule = pr.select(n);
const suffix = suffixes.get(rule);
return `${n}${suffix}`;
};
formatOrdinals(0); // '0th'
formatOrdinals(1); // '1st'
formatOrdinals(2); // '2nd'
formatOrdinals(3); // '3rd'
formatOrdinals(4); // '4th'
formatOrdinals(11); // '11th'
formatOrdinals(21); // '21st'
formatOrdinals(42); // '42nd'
formatOrdinals(103); // '103rd'
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Intl.PluralRules")}}
- {{jsxref("Intl")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/pluralrules | data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/pluralrules/supportedlocalesof/index.md | ---
title: Intl.PluralRules.supportedLocalesOf()
slug: Web/JavaScript/Reference/Global_Objects/Intl/PluralRules/supportedLocalesOf
page-type: javascript-static-method
browser-compat: javascript.builtins.Intl.PluralRules.supportedLocalesOf
---
{{JSRef}}
The **`Intl.PluralRules.supportedLocalesOf()`** static method returns an array containing those of the provided locales that are supported in plural rules without having to fall back to the runtime's default locale.
{{EmbedInteractiveExample("pages/js/intl-pluralrules-supportedlocalesof.html", "shorter")}}
## Syntax
```js-nolint
Intl.PluralRules.supportedLocalesOf(locales)
Intl.PluralRules.supportedLocalesOf(locales, options)
```
### Parameters
- `locales`
- : A string with a BCP 47 language tag, or an array of such strings. For the general form and interpretation of the `locales` argument, see [the parameter description on the `Intl` main page](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#locales_argument).
- `options` {{optional_inline}}
- : An object that may have the following property:
- `localeMatcher`
- : The locale matching algorithm to use. Possible values are `"lookup"` and `"best fit"`; the default is `"best fit"`. For information about this option, see the {{jsxref("Intl", "Intl", "#locale_identification_and_negotiation", 1)}} page.
### Return value
An array of strings representing a subset of the given locale tags that are supported in plural rules without having to fall back to the runtime's default locale.
## Examples
### Using supportedLocalesOf()
Assuming a runtime that supports Indonesian and German but not Balinese in plural rules, `supportedLocalesOf` returns the Indonesian and German language tags unchanged, even though `pinyin` collation is neither relevant to plural rules nor used with Indonesian, and a specialized German for Indonesia is unlikely to be supported. Note the specification of the `"lookup"` algorithm here — a `"best fit"` matcher might decide that Indonesian is an adequate match for Balinese since most Balinese speakers also understand Indonesian, and therefore return the Balinese language tag as well.
```js
const locales = ["ban", "id-u-co-pinyin", "de-ID"];
const options = { localeMatcher: "lookup" };
console.log(Intl.PluralRules.supportedLocalesOf(locales, options));
// ["id-u-co-pinyin", "de-ID"]
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Intl.PluralRules")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl | data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/listformat/index.md | ---
title: Intl.ListFormat
slug: Web/JavaScript/Reference/Global_Objects/Intl/ListFormat
page-type: javascript-class
browser-compat: javascript.builtins.Intl.ListFormat
---
{{JSRef}}
The **`Intl.ListFormat`** object enables language-sensitive list formatting.
{{EmbedInteractiveExample("pages/js/intl-listformat.html", "taller")}}
## Constructor
- {{jsxref("Intl/ListFormat/ListFormat", "Intl.ListFormat()")}}
- : Creates a new `Intl.ListFormat` object.
## Static methods
- {{jsxref("Intl/ListFormat/supportedLocalesOf", "Intl.ListFormat.supportedLocalesOf()")}}
- : Returns an array containing those of the provided locales that are supported without having to fall back to the runtime's default locale.
## Instance properties
These properties are defined on `Intl.ListFormat.prototype` and shared by all `Intl.ListFormat` instances.
- {{jsxref("Object/constructor", "Intl.ListFormat.prototype.constructor")}}
- : The constructor function that created the instance object. For `Intl.ListFormat` instances, the initial value is the {{jsxref("Intl/ListFormat/ListFormat", "Intl.ListFormat")}} constructor.
- `Intl.ListFormat.prototype[@@toStringTag]`
- : The initial value of the [`@@toStringTag`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/toStringTag) property is the string `"Intl.ListFormat"`. This property is used in {{jsxref("Object.prototype.toString()")}}.
## Instance methods
- {{jsxref("Intl/ListFormat/format", "Intl.ListFormat.prototype.format()")}}
- : Returns a language-specific formatted string representing the elements of the list.
- {{jsxref("Intl/ListFormat/formatToParts", "Intl.ListFormat.prototype.formatToParts()")}}
- : Returns an array of objects representing the different components that can be used to format a list of values in a locale-aware fashion.
- {{jsxref("Intl/ListFormat/resolvedOptions", "Intl.ListFormat.prototype.resolvedOptions()")}}
- : Returns a new object with properties reflecting the locale and style formatting options computed during the construction of the current {{jsxref("Intl.ListFormat")}} object.
## Examples
### Using format
The following example shows how to create a List formatter using the English language.
```js
const list = ["Motorcycle", "Bus", "Car"];
console.log(
new Intl.ListFormat("en-GB", { style: "long", type: "conjunction" }).format(
list,
),
);
// Motorcycle, Bus and Car
console.log(
new Intl.ListFormat("en-GB", { style: "short", type: "disjunction" }).format(
list,
),
);
// Motorcycle, Bus or Car
console.log(
new Intl.ListFormat("en-GB", { style: "narrow", type: "unit" }).format(list),
);
// Motorcycle Bus Car
```
### Using formatToParts
The following example shows how to create a List formatter returning formatted parts
```js
const list = ["Motorcycle", "Bus", "Car"];
console.log(
new Intl.ListFormat("en-GB", {
style: "long",
type: "conjunction",
}).formatToParts(list),
);
// [ { "type": "element", "value": "Motorcycle" },
// { "type": "literal", "value": ", " },
// { "type": "element", "value": "Bus" },
// { "type": "literal", "value": ", and " },
// { "type": "element", "value": "Car" } ];
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `Intl.ListFormat` in FormatJS](https://formatjs.io/docs/polyfills/intl-listformat/)
- {{jsxref("Intl")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/listformat | data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/listformat/format/index.md | ---
title: Intl.ListFormat.prototype.format()
slug: Web/JavaScript/Reference/Global_Objects/Intl/ListFormat/format
page-type: javascript-instance-method
browser-compat: javascript.builtins.Intl.ListFormat.format
---
{{JSRef}}
The **`format()`** method of {{jsxref("Intl.ListFormat")}} instances returns a string with a
language-specific representation of the list.
{{EmbedInteractiveExample("pages/js/intl-listformat.html", "taller")}}
## Syntax
```js-nolint
format()
format(list)
```
### Parameters
- `list`
- : An iterable object, such as an Array.
### Return value
A language-specific formatted string representing the elements of the list
## Description
The **`format()`** method returns a string that has been
formatted based on parameters provided in the `Intl.ListFormat` object. The
`locales` and `options` parameters customize the behavior of
`format()` and let applications specify the language conventions that
should be used to format the list.
## Examples
### Using format
The following example shows how to create a List formatter using the English language.
```js
const list = ["Motorcycle", "Bus", "Car"];
console.log(
new Intl.ListFormat("en-GB", { style: "long", type: "conjunction" }).format(
list,
),
);
// Motorcycle, Bus and Car
console.log(
new Intl.ListFormat("en-GB", { style: "short", type: "disjunction" }).format(
list,
),
);
// Motorcycle, Bus or Car
console.log(
new Intl.ListFormat("en-GB", { style: "narrow", type: "unit" }).format(list),
);
// Motorcycle Bus Car
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Intl.ListFormat")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/listformat | data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/listformat/resolvedoptions/index.md | ---
title: Intl.ListFormat.prototype.resolvedOptions()
slug: Web/JavaScript/Reference/Global_Objects/Intl/ListFormat/resolvedOptions
page-type: javascript-instance-method
browser-compat: javascript.builtins.Intl.ListFormat.resolvedOptions
---
{{JSRef}}
The **`resolvedOptions()`** method of {{jsxref("Intl.ListFormat")}} instances
returns a new object with properties reflecting the locale and style formatting
options computed during the construction of this `Intl.ListFormat` object.
{{EmbedInteractiveExample("pages/js/intl-listformat-prototype-resolvedoptions.html")}}
## Syntax
```js-nolint
resolvedOptions()
```
### Parameters
None.
### Return value
An object with properties reflecting the locale and formatting options computed during
the construction of the given {{jsxref("Intl.ListFormat")}} object.
## Description
The object returned by `resolvedOptions()` has the following properties:
- `locale`
- : The BCP 47 language tag for the locale actually used. If any Unicode extension
values were requested in the input BCP 47 language tag that led to this locale,
the key-value pairs that were requested and are supported for this locale are
included in `locale`.
- `style`
- : The value provided for this property in the `options` argument of the
constructor or the default value (`"long"`). Its value is either
`"long"`, `"short"`, or `"narrow"`.
- `type`
- : The value provided for this property in the `options` argument of the
constructor or the default value (`"conjunction"`). Its value is either
`"conjunction"`, `"disjunction"`, or `"unit"`.
## Examples
### Using resolvedOptions
```js
const deListFormatter = new Intl.ListFormat("de-DE", { style: "short" });
const usedOptions = de.resolvedOptions();
console.log(usedOptions.locale); // "de-DE"
console.log(usedOptions.style); // "short"
console.log(usedOptions.type); // "conjunction" (the default value)
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Intl.ListFormat")}}
- {{jsxref("Intl/NumberFormat/resolvedOptions", "Intl.NumberFormat.prototype.resolvedOptions()")}}
- {{jsxref("Intl/Collator/resolvedOptions", "Intl.Collator.prototype.resolvedOptions()")}}
- {{jsxref("Intl/DateTimeFormat/resolvedOptions", "Intl.DateTimeFormat.prototype.resolvedOptions()")}}
- {{jsxref("Intl/PluralRules/resolvedOptions", "Intl.PluralRules.prototype.resolvedOptions()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/listformat | data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/listformat/listformat/index.md | ---
title: Intl.ListFormat() constructor
slug: Web/JavaScript/Reference/Global_Objects/Intl/ListFormat/ListFormat
page-type: javascript-constructor
browser-compat: javascript.builtins.Intl.ListFormat.ListFormat
---
{{JSRef}}
The **`Intl.ListFormat()`** constructor creates {{jsxref("Intl.ListFormat")}} objects.
{{EmbedInteractiveExample("pages/js/intl-listformat.html", "taller")}}
## Syntax
```js-nolint
new Intl.ListFormat()
new Intl.ListFormat(locales)
new Intl.ListFormat(locales, options)
```
> **Note:** `Intl.ListFormat()` can only be constructed with [`new`](/en-US/docs/Web/JavaScript/Reference/Operators/new). Attempting to call it without `new` throws a {{jsxref("TypeError")}}.
### Parameters
- `locales` {{optional_inline}}
- : A string with a BCP 47 language tag or an {{jsxref("Intl.Locale")}} instance, or an array of such locale identifiers. For the general form and interpretation of the `locales` argument, see [the parameter description on the `Intl` main page](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#locales_argument).
- `options` {{optional_inline}}
- : An object containing the following properties, in the order they are retrieved (all of them are optional):
- `localeMatcher`
- : The locale matching algorithm to use. Possible values are `"lookup"` and `"best fit"`; the default is `"best fit"`. For information about this option, see [Locale identification and negotiation](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#locale_identification_and_negotiation).
- `type`
- : Indicates the type of grouping. Possible values are:
- `"conjunction"` (default)
- : For "and"-based grouping of the list items: "A, B, and C"
- `"disjunction"`
- : For "or"-based grouping of the list items: "A, B, or C"
- `"unit"`
- : For grouping the list items as a unit (neither "and"-based nor "or"-based): "A, B, C"
- `style`
- : The grouping style (for example, whether list separators and conjunctions are included). Possible values are:
- `"long"` (default)
- : E.g. "A, B, and C"
- `"short"`
- : E.g. "A, B, C"
- `"narrow"`
- : E.g. "A B C"
### Exceptions
- {{jsxref("RangeError")}}
- : Thrown if `locales` or `options` contain invalid values.
## Examples
### Using format
The following example shows how to create a List formatter using the English language.
```js
const list = ["Motorcycle", "Bus", "Car"];
console.log(
new Intl.ListFormat("en-GB", { style: "long", type: "conjunction" }).format(
list,
),
);
// Motorcycle, Bus and Car
console.log(new Intl.ListFormat("en-GB", { style: "long" }).format(list));
// Motorcycle, Bus and Car
console.log(new Intl.ListFormat("en-US", { style: "long" }).format(list));
// Motorcycle, Bus, and Car
console.log(
new Intl.ListFormat("en-GB", { style: "short", type: "conjunction" }).format(
list,
),
);
// Motorcycle, Bus and Car
console.log(
new Intl.ListFormat("en-US", { style: "short", type: "conjunction" }).format(
list,
),
);
// Motorcycle, Bus, & Car
console.log(
new Intl.ListFormat("en-GB", { style: "narrow", type: "conjunction" }).format(
list,
),
);
// Motorcycle, Bus, Car
console.log(
new Intl.ListFormat("en-GB", { style: "long", type: "disjunction" }).format(
list,
),
);
// Motorcycle, Bus or Car
console.log(
new Intl.ListFormat("en-GB", { style: "short", type: "disjunction" }).format(
list,
),
);
// Motorcycle, Bus or Car
console.log(
new Intl.ListFormat("en-GB", { style: "narrow", type: "disjunction" }).format(
list,
),
);
// Motorcycle, Bus or Car
console.log(new Intl.ListFormat("en-US", { style: "narrow" }).format(list));
// Motorcycle, Bus, Car
console.log(
new Intl.ListFormat("en-GB", { style: "narrow", type: "unit" }).format(list),
);
// Motorcycle Bus Car
console.log(
new Intl.ListFormat("en-US", { style: "long" }).format([
"30 degrees",
"15 minutes",
"50 seconds",
]),
);
// 30 degrees, 15 minutes, and 50 seconds
console.log(
new Intl.ListFormat("en-US", { style: "narrow" }).format([
"30 degrees",
"15 minutes",
"50 seconds",
]),
);
// 30 degrees, 15 minutes, 50 seconds
console.log(
new Intl.ListFormat("en-US", { style: "narrow", type: "unit" }).format([
"30°",
"15′",
"50″",
]),
);
// 30° 15′ 50″
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Intl.ListFormat")}}
- {{jsxref("Intl")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/listformat | data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/listformat/formattoparts/index.md | ---
title: Intl.ListFormat.prototype.formatToParts()
slug: Web/JavaScript/Reference/Global_Objects/Intl/ListFormat/formatToParts
page-type: javascript-instance-method
browser-compat: javascript.builtins.Intl.ListFormat.formatToParts
---
{{JSRef}}
The **`formatToParts()`** method of {{jsxref("Intl.ListFormat")}} instances
returns an {{jsxref("Array")}} of objects representing the different components that
can be used to format a list of values in a locale-aware fashion.
{{EmbedInteractiveExample("pages/js/intl-listformat-prototype-formattoparts.html", "taller")}}
## Syntax
```js-nolint
formatToParts(list)
```
### Parameters
- `list`
- : An iterable object, such as an {{jsxref("Array")}}, to be formatted according to a locale.
### Return value
An {{jsxref("Array")}} of components which contains the formatted parts from the list.
## Description
Whereas {{jsxref("Intl/ListFormat/format", "Intl.ListFormat.prototype.format()")}} returns a string being the formatted version
of the list (according to the given locale and style options),
`formatToParts()` returns an array of the different components of the
formatted string.
Each element of the resulting array has two properties: `type` and
`value`. The `type` property may be either
`"element"`, which refers to a value from the list, or
`"literal"` which refers to a linguistic construct. The `value`
property gives the content, as a string, of the token.
The locale and style options used for formatting are given when constructing the
{{jsxref("Intl.ListFormat")}} instance.
## Examples
### Using formatToParts
```js
const fruits = ["Apple", "Orange", "Pineapple"];
const myListFormat = new Intl.ListFormat("en-GB", {
style: "long",
type: "conjunction",
});
console.table(myListFormat.formatToParts(fruits));
// [
// { "type": "element", "value": "Apple" },
// { "type": "literal", "value": ", " },
// { "type": "element", "value": "Orange" },
// { "type": "literal", "value": ", and " },
// { "type": "element", "value": "Pineapple" }
// ]
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Intl.ListFormat")}}
- {{jsxref("Intl/ListFormat/format", "Intl.ListFormat.prototype.format()")}}
- {{jsxref("Intl/RelativeTimeFormat/formatToParts", "Intl.RelativeTimeFormat.prototype.formatToParts()")}}
- {{jsxref("Intl/NumberFormat/formatToParts", "Intl.NumberFormat.prototype.formatToParts()")}}
- {{jsxref("Intl/DateTimeFormat/formatToParts", "Intl.DateTimeFormat.prototype.formatToParts()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/listformat | data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/listformat/supportedlocalesof/index.md | ---
title: Intl.ListFormat.supportedLocalesOf()
slug: Web/JavaScript/Reference/Global_Objects/Intl/ListFormat/supportedLocalesOf
page-type: javascript-static-method
browser-compat: javascript.builtins.Intl.ListFormat.supportedLocalesOf
---
{{JSRef}}
The **`Intl.ListFormat.supportedLocalesOf()`** static method returns an array containing those of the provided locales that are supported in list formatting without having to fall back to the runtime's default locale.
## Syntax
```js-nolint
Intl.ListFormat.supportedLocalesOf(locales)
Intl.ListFormat.supportedLocalesOf(locales, options)
```
### Parameters
- `locales`
- : A string with a BCP 47 language tag, or an array of such strings. For the general form and interpretation of the `locales` argument, see [the parameter description on the `Intl` main page](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#locales_argument).
- `options` {{optional_inline}}
- : An object that may have the following property:
- `localeMatcher`
- : The locale matching algorithm to use. Possible values are `"lookup"` and `"best fit"`; the default is `"best fit"`. For information about this option, see the {{jsxref("Intl", "Intl", "#locale_identification_and_negotiation", 1)}} page.
### Return value
An array of strings representing a subset of the given locale tags that are supported in list formatting without having to fall back to the runtime's default locale.
## Examples
### Using supportedLocalesOf()
Assuming a runtime that supports Indonesian and German but not Balinese in list formatting, `supportedLocalesOf` returns the Indonesian and German language tags unchanged, even though `pinyin` collation is neither relevant to list formatting nor used with Indonesian, and a specialized German for Indonesia is unlikely to be supported. Note the specification of the `"lookup"` algorithm here — a `"best fit"` matcher might decide that Indonesian is an adequate match for Balinese since most Balinese speakers also understand Indonesian, and therefore return the Balinese language tag as well.
```js
const locales = ["ban", "id-u-co-pinyin", "de-ID"];
const options = { localeMatcher: "lookup" };
console.log(Intl.ListFormat.supportedLocalesOf(locales, options));
// ["id-u-co-pinyin", "de-ID"]
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Intl.ListFormat")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl | data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/relativetimeformat/index.md | ---
title: Intl.RelativeTimeFormat
slug: Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat
page-type: javascript-class
browser-compat: javascript.builtins.Intl.RelativeTimeFormat
---
{{JSRef}}
The **`Intl.RelativeTimeFormat`** object enables language-sensitive relative time formatting.
{{EmbedInteractiveExample("pages/js/intl-relativetimeformat.html")}}
## Constructor
- {{jsxref("Intl/RelativeTimeFormat/RelativeTimeFormat", "Intl.RelativeTimeFormat()")}}
- : Creates a new `Intl.RelativeTimeFormat` object.
## Static methods
- {{jsxref("Intl/RelativeTimeFormat/supportedLocalesOf", "Intl.RelativeTimeFormat.supportedLocalesOf()")}}
- : Returns an array containing those of the provided locales that are supported without having to fall back to the runtime's default locale.
## Instance properties
These properties are defined on `Intl.RelativeTimeFormat.prototype` and shared by all `Intl.RelativeTimeFormat` instances.
- {{jsxref("Object/constructor", "Intl.RelativeTimeFormat.prototype.constructor")}}
- : The constructor function that created the instance object. For `Intl.RelativeTimeFormat` instances, the initial value is the {{jsxref("Intl/RelativeTimeFormat/RelativeTimeFormat", "Intl.RelativeTimeFormat")}} constructor.
- `Intl.RelativeTimeFormat.prototype[@@toStringTag]`
- : The initial value of the [`@@toStringTag`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/toStringTag) property is the string `"Intl.RelativeTimeFormat"`. This property is used in {{jsxref("Object.prototype.toString()")}}.
## Instance methods
- {{jsxref("Intl/RelativeTimeFormat/format", "Intl.RelativeTimeFormat.prototype.format()")}}
- : Formats a `value` and a `unit` according to the locale and formatting options of the given `Intl.RelativeTimeFormat` object.
- {{jsxref("Intl/RelativeTimeFormat/formatToParts", "Intl.RelativeTimeFormat.prototype.formatToParts()")}}
- : Returns an {{jsxref("Array")}} of objects representing the relative time format in parts that can be used for custom locale-aware formatting.
- {{jsxref("Intl/RelativeTimeFormat/resolvedOptions", "Intl.RelativeTimeFormat.prototype.resolvedOptions()")}}
- : Returns a new object with properties reflecting the locale and formatting options computed during initialization of the object.
## Examples
### Basic format usage
The following example shows how to use a relative time formatter for the English language.
```js
// Create a relative time formatter in your locale
// with default values explicitly passed in.
const rtf = new Intl.RelativeTimeFormat("en", {
localeMatcher: "best fit", // other values: "lookup"
numeric: "always", // other values: "auto"
style: "long", // other values: "short" or "narrow"
});
// Format relative time using negative value (-1).
rtf.format(-1, "day"); // "1 day ago"
// Format relative time using positive value (1).
rtf.format(1, "day"); // "in 1 day"
```
### Using formatToParts
The following example shows how to create a relative time formatter returning formatted parts.
```js
const rtf = new Intl.RelativeTimeFormat("en", { numeric: "auto" });
// Format relative time using the day unit.
rtf.formatToParts(-1, "day");
// [{ type: "literal", value: "yesterday"}]
rtf.formatToParts(100, "day");
// [
// { type: "literal", value: "in " },
// { type: "integer", value: "100", unit: "day" },
// { type: "literal", value: " days" }
// ]
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `Intl.RelativeTimeFormat` in FormatJS](https://formatjs.io/docs/polyfills/intl-relativetimeformat/)
- {{jsxref("Intl")}}
- [`Intl.RelativeTimeFormat`](https://v8.dev/features/intl-relativetimeformat) on v8.dev (2018)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/relativetimeformat | data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/relativetimeformat/format/index.md | ---
title: Intl.RelativeTimeFormat.prototype.format()
slug: Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/format
page-type: javascript-instance-method
browser-compat: javascript.builtins.Intl.RelativeTimeFormat.format
---
{{JSRef}}
The **`format()`** method of {{jsxref("Intl.RelativeTimeFormat")}} instances formats a `value` and `unit` according to the locale and formatting options of this `Intl.RelativeTimeFormat` object.
{{EmbedInteractiveExample("pages/js/intl-relativetimeformat-prototype-format.html")}}
## Syntax
```js-nolint
format(value, unit)
```
### Parameters
- `value`
- : Numeric value to use in the internationalized relative time message.
- `unit`
- : Unit to use in the relative time internationalized message. Possible values are: `"year"`, `"quarter"`, `"month"`, `"week"`, `"day"`, `"hour"`, `"minute"`, `"second"`. Plural forms are also permitted.
### Return value
A string representing the given `value` and `unit` formatted according to the locale and formatting options of this {{jsxref("Intl.RelativeTimeFormat")}} object.
## Examples
### Basic format usage
The following example shows how to create a relative time formatter using the English language.
```js
// Create a relative time formatter in your locale
// with default values explicitly passed in.
const rtf = new Intl.RelativeTimeFormat("en", {
localeMatcher: "best fit", // other values: "lookup"
numeric: "always", // other values: "auto"
style: "long", // other values: "short" or "narrow"
});
// Format relative time using negative value (-1).
rtf.format(-1, "day"); // "1 day ago"
// Format relative time using positive value (1).
rtf.format(1, "day"); // "in 1 day"
```
### Using the auto option
If `numeric:auto` option is passed, it will produce the string `yesterday`, `today`, or `tomorrow` instead of `1 day ago`, `in 0 days`, or `in 1 day`. This allows to not always have to use numeric values in the output.
```js
// Create a relative time formatter in your locale
// with numeric: "auto" option value passed in.
const rtf = new Intl.RelativeTimeFormat("en", { numeric: "auto" });
// Format relative time using negative value (-1).
rtf.format(-1, "day"); // "yesterday"
rtf.format(0, "day"); // "today"
// Format relative time using positive day unit (1).
rtf.format(1, "day"); // "tomorrow"
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Intl.RelativeTimeFormat")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/relativetimeformat | data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/relativetimeformat/resolvedoptions/index.md | ---
title: Intl.RelativeTimeFormat.prototype.resolvedOptions()
slug: Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/resolvedOptions
page-type: javascript-instance-method
browser-compat: javascript.builtins.Intl.RelativeTimeFormat.resolvedOptions
---
{{JSRef}}
The **`resolvedOptions()`** method of {{jsxref("Intl.RelativeTimeFormat")}} instances returns a new object with properties reflecting the locale and relative time formatting options computed during initialization of this `Intl.RelativeTimeFormat` object.
{{EmbedInteractiveExample("pages/js/intl-relativetimeformat-prototype-resolvedoptions.html")}}
## Syntax
```js-nolint
resolvedOptions()
```
### Parameters
None.
### Return value
A new object with properties reflecting the locale and number formatting options computed during the initialization of the given {{jsxref("Intl.RelativeTimeFormat")}} object.
## Description
The resulting object has the following properties:
- `locale`
- : The BCP 47 language tag for the locale actually used. If any Unicode extension values were requested in the input BCP 47 language tag that led to this locale, the key-value pairs that were requested and are supported for this locale are included in `locale`.
- `style`
- : The length of the internationalized message. Possible values are:
- `"long"` (default, e.g., `in 1 month`)
- `"short"` (e.g., `in 1 mo.`),
- or `"narrow"` (e.g., `in 1 mo.`). The narrow style could be similar to the short style for some locales.
- `numeric`
- : The format of output message. Possible values are:
- `"always"` (default, e.g., `1 day ago`),
- or `"auto"` (e.g., `yesterday`). The `"auto"` value allows to not always have to use numeric values in the output.
- `numberingSystem`
- : The value requested using the Unicode extension key `"nu"` or filled in as a default.
## Examples
### Using the resolvedOptions() method
```js
const de = new Intl.RelativeTimeFormat("de-DE");
const usedOptions = de.resolvedOptions();
usedOptions.locale; // "de-DE"
usedOptions.style; // "long"
usedOptions.numeric; // "always"
usedOptions.numberingSystem; // "latn"
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Intl.RelativeTimeFormat")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/relativetimeformat | data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/relativetimeformat/relativetimeformat/index.md | ---
title: Intl.RelativeTimeFormat() constructor
slug: Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/RelativeTimeFormat
page-type: javascript-constructor
browser-compat: javascript.builtins.Intl.RelativeTimeFormat.RelativeTimeFormat
---
{{JSRef}}
The **`Intl.RelativeTimeFormat()`** constructor creates {{jsxref("Intl.RelativeTimeFormat")}} objects.
## Syntax
```js-nolint
new Intl.RelativeTimeFormat()
new Intl.RelativeTimeFormat(locales)
new Intl.RelativeTimeFormat(locales, options)
```
> **Note:** `Intl.RelativeTimeFormat()` can only be constructed with [`new`](/en-US/docs/Web/JavaScript/Reference/Operators/new). Attempting to call it without `new` throws a {{jsxref("TypeError")}}.
### Parameters
- `locales` {{optional_inline}}
- : A string with a BCP 47 language tag or an {{jsxref("Intl.Locale")}} instance, or an array of such locale identifiers. For the general form and interpretation of the `locales` argument, see [the parameter description on the `Intl` main page](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#locales_argument).
The following Unicode extension key is allowed:
- `nu`
- : See [`numberingSystem`](#numberingsystem).
This key can also be set with `options` (as listed below). When both are set, the `options` property takes precedence.
- `options` {{optional_inline}}
- : An object containing the following properties, in the order they are retrieved (all of them are optional):
- `localeMatcher`
- : The locale matching algorithm to use. Possible values are `"lookup"` and `"best fit"`; the default is `"best fit"`. For information about this option, see [Locale identification and negotiation](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#locale_identification_and_negotiation).
- `numberingSystem`
- : The numbering system to use for number formatting, such as `"arab"`, `"hans"`, `"mathsans"`, and so on. For a list of supported numbering system types, see [`Intl.Locale.prototype.getNumberingSystems()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Locale/getNumberingSystems#supported_numbering_system_types). This option can also be set through the `nu` Unicode extension key; if both are provided, this `options` property takes precedence.
- `style`
- : The style of the formatted relative time. Possible values are:
- `"long"` (default)
- : E.g., "in 1 month"
- `"short"`
- : E.g., "in 1 mo."
- `"narrow"`
- : E.g., "in 1 mo.". The narrow style could be similar to the short style for some locales.
- `numeric`
- : Whether to use numeric values in the output. Possible values are `"always"` and `"auto"`; the default is `"always"`. When set to `"auto"`, the output may use more idiomatic phrasing such as `"yesterday"` instead of `"1 day ago"`.
### Exceptions
- {{jsxref("RangeError")}}
- : Thrown if `locales` or `options` contain invalid values.
## Examples
### Basic format usage
The following example shows how to create a relative time formatter using the English language.
```js
// Create a relative time formatter in your locale
// with default values explicitly passed in.
const rtf = new Intl.RelativeTimeFormat("en", {
localeMatcher: "best fit", // other values: "lookup"
numeric: "always", // other values: "auto"
style: "long", // other values: "short" or "narrow"
});
// Format relative time using negative value (-1).
rtf.format(-1, "day"); // "1 day ago"
// Format relative time using positive value (1).
rtf.format(1, "day"); // "in 1 day"
```
### Using the auto option
If `numeric:auto` option is passed, it will produce the string `yesterday` or `tomorrow` instead of `1 day ago` or `in 1 day`. This allows to not always have to use numeric values in the output.
```js
// Create a relative time formatter in your locale
// with numeric: "auto" option value passed in.
const rtf = new Intl.RelativeTimeFormat("en", { numeric: "auto" });
// Format relative time using negative value (-1).
rtf.format(-1, "day"); // "yesterday"
// Format relative time using positive day unit (1).
rtf.format(1, "day"); // "tomorrow"
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Intl.RelativeTimeFormat")}}
- {{jsxref("Intl")}}
- [`Intl.RelativeTimeFormat`](https://v8.dev/features/intl-relativetimeformat) on v8.dev (2018)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/relativetimeformat | data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/relativetimeformat/formattoparts/index.md | ---
title: Intl.RelativeTimeFormat.prototype.formatToParts()
slug: Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/formatToParts
page-type: javascript-instance-method
browser-compat: javascript.builtins.Intl.RelativeTimeFormat.formatToParts
---
{{JSRef}}
The **`formatToParts()`** method of {{jsxref("Intl.RelativeTimeFormat")}} instances returns an {{jsxref("Array")}} of objects representing the relative time format in parts that can be used for custom locale-aware formatting.
{{EmbedInteractiveExample("pages/js/intl-relativetimeformat-prototype-formattoparts.html")}}
## Syntax
```js-nolint
formatToParts(value, unit)
```
### Parameters
- `value`
- : Numeric value to use in the internationalized relative time message.
- `unit`
- : Unit to use in the relative time internationalized message. Possible values are: `"year"`, `"quarter"`, `"month"`, `"week"`, `"day"`, `"hour"`, `"minute"`, `"second"`. Plural forms are also permitted.
### Return value
An {{jsxref("Array")}} of objects containing the formatted relative time in parts.
## Description
The `Intl.RelativeTimeFormat.prototype.formatToParts` method is a version of the format method which it returns an array of objects which represent "parts" of the object, separating the formatted number into its constituent parts and separating it from other surrounding text. These objects have two properties: type a `NumberFormat` formatToParts type, and value, which is the String which is the component of the output. If a "part" came from `NumberFormat`, it will have a unit property which indicates the unit being formatted; literals which are part of the larger frame will not have this property.
## Examples
### Using formatToParts
```js
const rtf = new Intl.RelativeTimeFormat("en", { numeric: "auto" });
// Format relative time using the day unit
rtf.formatToParts(-1, "day");
// [{ type: "literal", value: "yesterday"}]
rtf.formatToParts(100, "day");
// [
// { type: "literal", value: "in " },
// { type: "integer", value: "100", unit: "day" },
// { type: "literal", value: " days" }
// ]
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Intl.RelativeTimeFormat")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/relativetimeformat | data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/relativetimeformat/supportedlocalesof/index.md | ---
title: Intl.RelativeTimeFormat.supportedLocalesOf()
slug: Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/supportedLocalesOf
page-type: javascript-static-method
browser-compat: javascript.builtins.Intl.RelativeTimeFormat.supportedLocalesOf
---
{{JSRef}}
The **`Intl.RelativeTimeFormat.supportedLocalesOf()`** static method returns an array containing those of the provided locales that are supported in relative time formatting without having to fall back to the runtime's default locale.
{{EmbedInteractiveExample("pages/js/intl-relativetimeformat-supportedlocalesof.html", "shorter")}}
## Syntax
```js-nolint
Intl.RelativeTimeFormat.supportedLocalesOf(locales)
Intl.RelativeTimeFormat.supportedLocalesOf(locales, options)
```
### Parameters
- `locales`
- : A string with a BCP 47 language tag, or an array of such strings. For the general form and interpretation of the `locales` argument, see [the parameter description on the `Intl` main page](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#locales_argument).
- `options` {{optional_inline}}
- : An object that may have the following property:
- `localeMatcher`
- : The locale matching algorithm to use. Possible values are `"lookup"` and `"best fit"`; the default is `"best fit"`. For information about this option, see the {{jsxref("Intl", "Intl", "#locale_identification_and_negotiation", 1)}} page.
### Return value
An array of strings representing a subset of the given locale tags that are supported in relative time formatting without having to fall back to the runtime's default locale.
## Examples
### Using supportedLocalesOf()
Assuming a runtime that supports Indonesian and German but not Balinese in relative time formatting, `supportedLocalesOf` returns the Indonesian and German language tags unchanged, even though `pinyin` collation is neither relevant to relative time formatting nor used with Indonesian, and a specialized German for Indonesia is unlikely to be supported. Note the specification of the `"lookup"` algorithm here — a `"best fit"` matcher might decide that Indonesian is an adequate match for Balinese since most Balinese speakers also understand Indonesian, and therefore return the Balinese language tag as well.
```js
const locales = ["ban", "id-u-co-pinyin", "de-ID"];
const options = { localeMatcher: "lookup" };
console.log(Intl.RelativeTimeFormat.supportedLocalesOf(locales, options));
// ["id-u-co-pinyin", "de-ID"]
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Intl.RelativeTimeFormat")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl | data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/locale/index.md | ---
title: Intl.Locale
slug: Web/JavaScript/Reference/Global_Objects/Intl/Locale
page-type: javascript-class
browser-compat: javascript.builtins.Intl.Locale
---
{{JSRef}}
The **`Intl.Locale`** object is a standard built-in property of the Intl object that represents a Unicode locale identifier.
{{EmbedInteractiveExample("pages/js/intl-locale.html")}}
## Description
The **`Intl.Locale`** object was created to allow for easier manipulation of Unicode locales. Unicode represents locales with a string, called a _locale identifier_. The locale identifier consists of a _language identifier_ and _extension tags_. Language identifiers are the core of the locale, consisting of _language_, _script_, and _region subtags_. Additional information about the locale is stored in the optional _extension tags_. Extension tags hold information about locale aspects such as calendar type, clock type, and numbering system type.
Traditionally, the Intl API used strings to represent locales, just as Unicode does. This is a simple and lightweight solution that works well. Adding a Locale class, however, adds ease of parsing and manipulating the language, script, and region, as well as extension tags. The following properties of `Intl.Locale` correspond to Unicode locale identifier subtags:
| Property | Corresponding subtag |
| ------------------------------------------------------------ | ---------------------------- |
| {{jsxref("Intl/Locale/language", "language")}} | `language` (first part) |
| {{jsxref("Intl/Locale/script", "script")}} | `script` (second part) |
| {{jsxref("Intl/Locale/region", "region")}} | `region` (second/third part) |
| {{jsxref("Intl/Locale/calendar", "calendar")}} | `ca` (extension) |
| {{jsxref("Intl/Locale/caseFirst", "caseFirst")}} | `kf` (extension) |
| {{jsxref("Intl/Locale/collation", "collation")}} | `co` (extension) |
| {{jsxref("Intl/Locale/hourCycle", "hourCycle")}} | `hc` (extension) |
| {{jsxref("Intl/Locale/numberingSystem", "numberingSystem")}} | `nu` (extension) |
| {{jsxref("Intl/Locale/numeric", "numeric")}} | `kn` (extension) |
The information above is exactly provided as-is when the `Locale` object is constructed, without consulting any external database. The `Intl.Locale` object additionally provides some methods that return information about the locale's real-world information, such as available calendars, collations, and numbering systems.
## Constructor
- {{jsxref("Intl/Locale/Locale", "Intl.Locale()")}}
- : Creates a new `Locale` object.
## Instance properties
These properties are defined on `Intl.Locale.prototype` and shared by all `Intl.Locale` instances.
- {{jsxref("Intl/Locale/baseName", "Intl.Locale.prototype.baseName")}}
- : Returns basic, core information about the `Locale` in the form of a substring of the complete data string.
- {{jsxref("Intl/Locale/calendar", "Intl.Locale.prototype.calendar")}}
- : Returns the part of the `Locale` that indicates the Locale's calendar era.
- {{jsxref("Intl/Locale/caseFirst", "Intl.Locale.prototype.caseFirst")}}
- : Returns whether case is taken into account for the locale's collation rules.
- {{jsxref("Intl/Locale/collation", "Intl.Locale.prototype.collation")}}
- : Returns the collation type for the `Locale`, which is used to order strings according to the locale's rules.
- {{jsxref("Object/constructor", "Intl.Locale.prototype.constructor")}}
- : The constructor function that created the instance object. For `Intl.Locale` instances, the initial value is the {{jsxref("Intl/Locale/Locale", "Intl.Locale")}} constructor.
- {{jsxref("Intl/Locale/hourCycle", "Intl.Locale.prototype.hourCycle")}}
- : Returns the time keeping format convention used by the locale.
- {{jsxref("Intl/Locale/language", "Intl.Locale.prototype.language")}}
- : Returns the language associated with the locale.
- {{jsxref("Intl/Locale/numberingSystem", "Intl.Locale.prototype.numberingSystem")}}
- : Returns the numeral system used by the locale.
- {{jsxref("Intl/Locale/numeric", "Intl.Locale.prototype.numeric")}}
- : Returns whether the locale has special collation handling for numeric characters.
- {{jsxref("Intl/Locale/region", "Intl.Locale.prototype.region")}}
- : Returns the region of the world (usually a country) associated with the locale.
- {{jsxref("Intl/Locale/script", "Intl.Locale.prototype.script")}}
- : Returns the script used for writing the particular language used in the locale.
- `Intl.Locale.prototype[@@toStringTag]`
- : The initial value of the [`@@toStringTag`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/toStringTag) property is the string `"Intl.Locale"`. This property is used in {{jsxref("Object.prototype.toString()")}}.
## Instance methods
- {{jsxref("Intl/Locale/getCalendars", "Intl.Locale.prototype.getCalendars()")}}
- : Returns an {{jsxref("Array")}} of available calendar identifiers, according to the locale's rules.
- {{jsxref("Intl/Locale/getCollations", "Intl.Locale.prototype.getCollations()")}}
- : Returns an {{jsxref("Array")}} of the collation types for the `Locale`.
- {{jsxref("Intl/Locale/getHourCycles", "Intl.Locale.prototype.getHourCycles()")}}
- : Returns an {{jsxref("Array")}} of hour cycle identifiers, indicating either the 12-hour clock ("h12"), the Japanese 12-hour clock ("h11"), the 24-hour clock ("h23"), or the unused format "h24".
- {{jsxref("Intl/Locale/getNumberingSystems", "Intl.Locale.prototype.getNumberingSystems()")}}
- : Returns an {{jsxref("Array")}} of numbering system identifiers available according to the locale's rules.
- {{jsxref("Intl/Locale/getTextInfo", "Intl.Locale.prototype.getTextInfo()")}}
- : Returns the part indicating the ordering of characters `ltr` (left-to-right) or `rtl` (right-to-left).
- {{jsxref("Intl/Locale/getTimeZones", "Intl.Locale.prototype.getTimeZones()")}}
- : Returns an {{jsxref("Array")}} of time zone identifiers, associated with the `Locale`.
- {{jsxref("Intl/Locale/getWeekInfo", "Intl.Locale.prototype.getWeekInfo()")}}
- : Returns [UTS 35's Week Elements](https://www.unicode.org/reports/tr35/tr35-dates.html#Date_Patterns_Week_Elements) according to the locale rules.
- {{jsxref("Intl/Locale/maximize", "Intl.Locale.prototype.maximize()")}}
- : Gets the most likely values for the language, script, and region of the locale based on existing values.
- {{jsxref("Intl/Locale/minimize", "Intl.Locale.prototype.minimize()")}}
- : Attempts to remove information about the locale that would be added by calling {{jsxref("Intl/Locale/maximize", "maximize()")}}.
- {{jsxref("Intl/Locale/toString", "Intl.Locale.prototype.toString()")}}
- : Returns the Locale's full locale identifier string.
## Examples
### Basic usage
At its very simplest, the {{jsxref("Intl/Locale/Locale", "Intl.Locale()")}} constructor takes a locale identifier string as its argument:
```js
const us = new Intl.Locale("en-US");
```
### Using the Locale constructor with an options object
The constructor also takes an optional configuration object argument, which can contain any of several extension types. For example, set the {{jsxref("Intl/Locale/hourCycle", "hourCycle")}} property of the configuration object to your desired hour cycle type, and then pass it into the constructor:
```js
const us12hour = new Intl.Locale("en-US", { hourCycle: "h12" });
console.log(us12hour.hourCycle); // Prints "h12"
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `Intl.Locale` in FormatJS](https://formatjs.io/docs/polyfills/intl-locale/)
- {{jsxref("Intl")}}
- [Canonical Unicode Locale Identifiers](https://www.unicode.org/reports/tr35/#Canonical_Unicode_Locale_Identifiers) in the Unicode locale data markup language spec
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/locale | data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/locale/tostring/index.md | ---
title: Intl.Locale.prototype.toString()
slug: Web/JavaScript/Reference/Global_Objects/Intl/Locale/toString
page-type: javascript-instance-method
browser-compat: javascript.builtins.Intl.Locale.toString
---
{{JSRef}}
The **`toString()`** method of {{jsxref("Intl.Locale")}} instances returns this Locale's full [locale identifier string](https://www.unicode.org/reports/tr35/#Unicode_locale_identifier).
{{EmbedInteractiveExample("pages/js/intl-locale-prototype-tostring.html", "taller")}}
## Syntax
```js-nolint
toString()
```
### Parameters
None.
### Return value
The _locale_'s Unicode locale identifier string.
## Description
The `Locale` object is a JavaScript representation of a concept
Unicode locale identifier. Information about a particular locale (language, script,
calendar type, etc.) can be encoded in a locale identifier string. To make it easier
to work with these locale identifiers, the `Locale` object was
introduced to JavaScript. Calling the `toString` method on a Locale object
will return the identifier string for that particular Locale. The
`toString` method allows `Locale` instances to be
provided as an argument to existing `Intl` constructors, serialized in
JSON, or any other context where an exact string representation is useful.
## Examples
### Using toString
```js
const myLocale = new Intl.Locale("fr-Latn-FR", {
hourCycle: "h12",
calendar: "gregory",
});
console.log(myLocale.baseName); // Prints "fr-Latn-FR"
console.log(myLocale.toString()); // Prints "fr-Latn-FR-u-ca-gregory-hc-h12"
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Intl.Locale")}}
- {{jsxref("Intl/Locale/baseName", "baseName")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/locale | data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/locale/basename/index.md | ---
title: Intl.Locale.prototype.baseName
slug: Web/JavaScript/Reference/Global_Objects/Intl/Locale/baseName
page-type: javascript-instance-accessor-property
browser-compat: javascript.builtins.Intl.Locale.baseName
---
{{JSRef}}
The **`baseName`** accessor property of {{jsxref("Intl.Locale")}} instances returns a substring of this locale's string representation, containing core information about this locale.
## Description
An {{jsxref("Intl.Locale")}} object represents a parsed local and options for that locale. The `baseName` property returns basic, core information about the Locale in the form of a substring of the complete data string. Specifically, the property returns the substring containing the language, and the script and region if available.
`baseName` returns the `language ["-" script] ["-" region] *("-" variant)` subsequence of the [unicode_language_id grammar](https://www.unicode.org/reports/tr35/#Identifiers).
## Examples
### Basic Example
```js
const myLoc = new Intl.Locale("fr-Latn-CA"); // Sets locale to Canadian French
console.log(myLoc.toString()); // Prints out "fr-Latn-CA-u-ca-gregory"
console.log(myLoc.baseName); // Prints out "fr-Latn-CA"
```
### Example with options in the input string
```js
// Sets language to Japanese, region to Japan,
// calendar to Gregorian, hour cycle to 24 hours
const japan = new Intl.Locale("ja-JP-u-ca-gregory-hc-24");
console.log(japan.toString()); // Prints out "ja-JP-u-ca-gregory-hc-h24"
console.log(japan.baseName); // Prints out "ja-JP"
```
### Example with options that override input string
```js
// Input string indicates language as Dutch and region as Belgium,
// but options object overrides the region and sets it to the Netherlands
const dutch = new Intl.Locale("nl-Latn-BE", { region: "NL" });
console.log(dutch.baseName); // Prints out "nl-Latn-NL"
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Intl.Locale")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/locale | data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/locale/maximize/index.md | ---
title: Intl.Locale.prototype.maximize()
slug: Web/JavaScript/Reference/Global_Objects/Intl/Locale/maximize
page-type: javascript-instance-method
browser-compat: javascript.builtins.Intl.Locale.maximize
---
{{JSRef}}
The **`maximize()`** method of {{jsxref("Intl.Locale")}} instances gets the
most likely values for the language, script, and region of this locale based on
existing values.
{{EmbedInteractiveExample("pages/js/intl-locale-prototype-maximize.html")}}
## Syntax
```js-nolint
maximize()
```
### Parameters
None.
### Return value
A {{jsxref("Intl.Locale")}} instance whose `baseName` property returns
the result of the [Add Likely Subtags](https://www.unicode.org/reports/tr35/#Likely_Subtags) algorithm executed against _{{jsxref("Intl/Locale/baseName", "locale.baseName")}}_.
## Description
Sometimes, it is convenient to be able to identify the most likely locale language
identifier subtags based on an incomplete language ID. The Add Likely Subtags
algorithm gives us this functionality. For instance, given the language ID "en", the
algorithm would return "en-Latn-US", since English can only be written in the Latin
script, and is most likely to be used in the United States, as it is the largest
English-speaking country in the world. This functionality is provided to JavaScript
programmers via the `maximize()` method. `maximize()` only
affects the main subtags that comprise the [language identifier](https://www.unicode.org/reports/tr35/#Language_Locale_Field_Definitions): language, script, and region subtags.
Other subtags after the "-u" in the locale identifier are called extension subtags and
are not affected by the `maximize()` method. Examples of these subtags
include {{jsxref("Intl/Locale/hourCycle", "hourCycle")}},
{{jsxref("Intl/Locale/calendar", "calendar")}}, and {{jsxref("Intl/Locale/numeric", "numeric")}}.
## Examples
### Using maximize
```js
const myLocale = new Intl.Locale("fr", {
hourCycle: "h12",
calendar: "gregory",
});
console.log(myLocale.baseName); // Prints "fr"
console.log(myLocale.toString()); // Prints "fr-u-ca-gregory-hc-h12"
const myLocMaximized = myLocale.maximize();
// Prints "fr-Latn-FR". The "Latn" and "FR" tags are added,
// since French is only written in the Latin script and is most likely to be spoken in France.
console.log(myLocMaximized.baseName);
// Prints "fr-Latn-FR-u-ca-gregory-hc-h12".
// Note that the extension tags (after "-u") remain unchanged.
console.log(myLocMaximized.toString());
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Intl.Locale")}}
- {{jsxref("Intl/Locale/baseName", "baseName")}}
- [Likely Subtags](https://www.unicode.org/reports/tr35/#Likely_Subtags) in the Unicode locale data markup language spec
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/locale | data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/locale/hourcycle/index.md | ---
title: Intl.Locale.prototype.hourCycle
slug: Web/JavaScript/Reference/Global_Objects/Intl/Locale/hourCycle
page-type: javascript-instance-accessor-property
browser-compat: javascript.builtins.Intl.Locale.hourCycle
---
{{JSRef}}
The **`hourCycle`** accessor property of {{jsxref("Intl.Locale")}} instances returns the hour cycle type for this locale.
## Description
There are 2 main types of time keeping conventions (clocks) used around the world: the 12 hour clock and the 24 hour clock. The `hourCycle` property's value is set at construction time, either through the `hc` key of the locale identifier or through the `hourCycle` option of the {{jsxref("Intl/Locale/Locale", "Intl.Locale()")}} constructor. The latter takes priority if they are both present; and if neither is present, the property has value `undefined`.
For a list of supported hour cycle types, see [`Intl.Locale.prototype.getHourCycles()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Locale/getHourCycles#supported_hour_cycle_types).
The set accessor of `hourCycle` is `undefined`. You cannot change this property directly.
## Examples
Like other locale subtags, the hour cycle type can be added to the {{jsxref("Intl.Locale")}} object via the locale string, or a configuration object argument to the constructor.
### Adding an hour cycle via the locale string
In the [Unicode locale string spec](https://www.unicode.org/reports/tr35/), hour cycle types are locale key "extension subtags". These subtags add additional data about the locale, and are added to locale identifiers by using the `-u` extension. Thus, the hour cycle type can be added to the initial locale identifier string that is passed into the {{jsxref("Intl/Locale/Locale", "Intl.Locale()")}} constructor. To add the hour cycle type, first add the `-u` extension key to the string. Next, add the `-hc` extension to indicate that you are adding an hour cycle. Finally, add the hour cycle type to the string.
```js
const locale = new Intl.Locale("fr-FR-u-hc-h23");
console.log(locale.hourCycle); // "h23"
```
### Adding an hour cycle via the configuration object argument
The {{jsxref("Intl/Locale/Locale", "Intl.Locale()")}} constructor has an optional configuration object argument, which can contain any of several extension types, including hour cycle types. Set the `hourCycle` property of the configuration object to your desired hour cycle type, and then pass it into the constructor.
```js
const locale = new Intl.Locale("en-US", { hourCycle: "h12" });
console.log(locale.hourCycle); // "h12"
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Intl.Locale")}}
- [`Intl.Locale.prototype.getHourCycles()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Locale/getHourCycles)
- [Unicode Hour Cycle Identifier](https://www.unicode.org/reports/tr35/#UnicodeHourCycleIdentifier) in the Unicode locale data markup language spec
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/locale | data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/locale/region/index.md | ---
title: Intl.Locale.prototype.region
slug: Web/JavaScript/Reference/Global_Objects/Intl/Locale/region
page-type: javascript-instance-accessor-property
browser-compat: javascript.builtins.Intl.Locale.region
---
{{JSRef}}
The **`region`** accessor property of {{jsxref("Intl.Locale")}} instances returns the region of the world (usually a country) associated with this locale.
## Description
The region is an essential part of the locale identifier, as it places the locale in a specific area of the world. Knowing the locale's region is vital to identifying differences between locales. For example, English is spoken in the United Kingdom and the United States of America, but there are differences in spelling and other language conventions between those two countries. Knowing the locale's region helps JavaScript programmers make sure that the content from their sites and applications is correctly displayed when viewed from different areas of the world.
## Examples
### Setting the region in the locale identifier string argument
The region is the third part of a valid Unicode language identifier string, and can be set by adding it to the locale identifier string that is passed into the {{jsxref("Intl/Locale/Locale", "Intl.Locale()")}} constructor. The region is a mandatory part of a
```js
const locale = new Intl.Locale("en-Latn-US");
console.log(locale.region); // Prints "US"
```
### Setting the region via the configuration object
The {{jsxref("Intl/Locale/Locale", "Intl.Locale()")}} constructor takes a configuration object, which can be used to set the region subtag and property.
```js
const locale = new Intl.Locale("fr-Latn", { region: "FR" });
console.log(locale.region); // Prints "FR"
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Intl.Locale")}}
- [Unicode region chart](https://unicode-org.github.io/cldr-staging/charts/latest/supplemental/territory_containment_un_m_49.html)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/locale | data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/locale/minimize/index.md | ---
title: Intl.Locale.prototype.minimize()
slug: Web/JavaScript/Reference/Global_Objects/Intl/Locale/minimize
page-type: javascript-instance-method
browser-compat: javascript.builtins.Intl.Locale.minimize
---
{{JSRef}}
The **`minimize()`** method of {{jsxref("Intl.Locale")}} instances attempts to
remove information about this locale that would be added by calling
{{jsxref("Intl/Locale/maximize", "maximize()")}}.
{{EmbedInteractiveExample("pages/js/intl-locale-prototype-minimize.html")}}
## Syntax
```js-nolint
minimize()
```
### Parameters
None.
### Return value
A {{jsxref("Intl.Locale")}} instance whose `baseName` property returns
the result of the [Remove Likely Subtags](https://www.unicode.org/reports/tr35/#Likely_Subtags) algorithm
executed against _{{jsxref("Intl/Locale/baseName", "locale.baseName")}}_.
## Description
This method carries out the reverse of {{jsxref("Intl/Locale/maximize", "maximize()")}},
removing any language, script, or region subtags from the locale language identifier
(essentially the contents of `baseName`). This is useful when there are
superfluous subtags in the language identifier; for instance, "en-Latn" can be
simplified to "en", since "Latn" is the only script used to write English.
`minimize()` only affects the main subtags that comprise
the [language identifier](https://www.unicode.org/reports/tr35/#Language_Locale_Field_Definitions):
language, script, and region subtags. Other subtags after the "-u"
in the locale identifier are called extension subtags and are not affected by the
`minimize()` method. Examples of these subtags include
{{jsxref("Intl/Locale/hourCycle", "hourCycle")}}, {{jsxref("Intl/Locale/calendar", "calendar")}}, and {{jsxref("Intl/Locale/numeric", "numeric")}}.
## Examples
### Using minimize
```js
const myLocale = new Intl.Locale("fr-Latn-FR", {
hourCycle: "h12",
calendar: "gregory",
});
console.log(myLocale.baseName); // Prints "fr-Latn-FR"
console.log(myLocale.toString()); // Prints "fr-Latn-FR-u-ca-gregory-hc-h12"
const myLocMinimized = myLocale.minimize();
// Prints "fr", since French is only written in the Latin script
// and is most likely to be spoken in France.
console.log(myLocMinimized.baseName);
// Prints "fr-u-ca-gregory-hc-h12".
// Note that the extension tags (after "-u") remain unchanged.
console.log(myLocMinimized.toString());
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Intl.Locale")}}
- {{jsxref("Intl/Locale/baseName", "baseName")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/locale | data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/locale/language/index.md | ---
title: Intl.Locale.prototype.language
slug: Web/JavaScript/Reference/Global_Objects/Intl/Locale/language
page-type: javascript-instance-accessor-property
browser-compat: javascript.builtins.Intl.Locale.language
---
{{JSRef}}
The **`language`** accessor property of {{jsxref("Intl.Locale")}} instances returns the language associated with this locale.
## Description
Language is one of the core features of a locale. The Unicode specification treats the language identifier of a locale as the language and the region together (to make a distinction between dialects and variations, e.g. British English vs. American English). The `language` property of a {{jsxref("Intl.Locale")}} returns strictly the locale's language subtag.
## Examples
### Setting the language in the locale identifier string argument
In order to be a valid Unicode locale identifier, a string must start with the language subtag. The main argument to the {{jsxref("Intl/Locale/Locale", "Intl.Locale()")}} constructor must be a valid Unicode locale identifier, so whenever the constructor is used, it must be passed an identifier with a language subtag.
```js
const locale = new Intl.Locale("en-Latn-US");
console.log(locale.language); // Prints "en"
```
### Overriding language via the configuration object
While the language subtag must be specified, the {{jsxref("Intl/Locale/Locale", "Intl.Locale()")}} constructor takes a configuration object, which can override the language subtag.
```js
const locale = new Intl.Locale("en-Latn-US", { language: "es" });
console.log(locale.language); // Prints "es"
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Intl.Locale")}}
- [Unicode language subtag](https://www.unicode.org/reports/tr35/#unicode_language_subtag_validity) in the Unicode locale data markup language spec
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/locale | data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/locale/calendar/index.md | ---
title: Intl.Locale.prototype.calendar
slug: Web/JavaScript/Reference/Global_Objects/Intl/Locale/calendar
page-type: javascript-instance-accessor-property
browser-compat: javascript.builtins.Intl.Locale.calendar
---
{{JSRef}}
The **`calendar`** accessor property of {{jsxref("Intl.Locale")}} instances returns the calendar type for this locale.
## Description
While most of the world uses the Gregorian calendar, there are several regional calendar eras used around the world. The `calendar` property's value is set at construction time, either through the `ca` key of the locale identifier or through the `calendar` option of the {{jsxref("Intl/Locale/Locale", "Intl.Locale()")}} constructor. The latter takes priority if they are both present; and if neither is present, the property has value `undefined`.
For a list of supported calendar types, see [`Intl.Locale.prototype.getCalendars()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Locale/getCalendars#supported_calendar_types).
The set accessor of `calendar` is `undefined`. You cannot change this property directly.
## Examples
Like other locale subtags, the calendar type can be added to the {{jsxref("Intl.Locale")}} object via the locale string, or a configuration object argument to the constructor.
### Adding a calendar type via the locale string
In the [Unicode locale string spec](https://www.unicode.org/reports/tr35/), calendar era types are locale key "extension subtags". These subtags add additional data about the locale, and are added to locale identifiers by using the `-u` extension. Thus, the calendar era type can be added to the initial locale identifier string that is passed into the {{jsxref("Intl/Locale/Locale", "Intl.Locale()")}} constructor. To add the calendar type, first add the `-u` extension to the string. Next, add the `-ca` extension to indicate that you are adding a calendar type. Finally, add the calendar era type to the string.
```js
const locale = new Intl.Locale("fr-FR-u-ca-buddhist");
console.log(locale.calendar); // Prints "buddhist"
```
### Adding a calendar type via the configuration object argument
The {{jsxref("Intl/Locale/Locale", "Intl.Locale()")}} constructor has an optional configuration object argument, which can contain any of several extension types, including calendars. Set the `calendar` property of the configuration object to your desired calendar era, and then pass it into the constructor.
```js
const locale = new Intl.Locale("fr-FR", { calendar: "buddhist" });
console.log(locale.calendar); // "buddhist"
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Intl.Locale")}}
- [`Intl.Locale.prototype.getCalendars()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Locale/getCalendars)
- [Unicode Calendar Identifier](https://www.unicode.org/reports/tr35/#UnicodeCalendarIdentifier) in the Unicode locale data markup language spec
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/locale | data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/locale/collation/index.md | ---
title: Intl.Locale.prototype.collation
slug: Web/JavaScript/Reference/Global_Objects/Intl/Locale/collation
page-type: javascript-instance-accessor-property
browser-compat: javascript.builtins.Intl.Locale.collation
---
{{JSRef}}
The **`collation`** accessor property of {{jsxref("Intl.Locale")}} instances returns the [collation type](https://www.unicode.org/reports/tr35/tr35-collation.html#CLDR_Collation) for this locale, which is used to order strings according to the locale's rules.
## Description
Collation is the process of ordering strings of characters. It is used whenever strings must be sorted and placed into a certain order, from search query results to ordering records in a database. While the idea of placing strings in order might seem trivial, the idea of order can vary from region to region and language to language. The `collation` property's value is set at construction time, either through the `co` key of the locale identifier or through the `collation` option of the {{jsxref("Intl/Locale/Locale", "Intl.Locale()")}} constructor. The latter takes priority if they are both present; and if neither is present, the property has value `undefined`.
For a list of supported collation types, see [`Intl.Locale.prototype.getCollations()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Locale/getCollations#supported_collation_types).
The set accessor of `collation` is `undefined`. You cannot change this property directly.
## Examples
Like other locale subtags, the collation type can be added to the {{jsxref("Intl.Locale")}} object via the locale string, or a configuration object argument to the constructor.
### Adding a collation type via the locale string
In the [Unicode locale string spec](https://www.unicode.org/reports/tr35/), collation types are locale key "extension subtags". These subtags add additional data about the locale, and are added to locale identifiers by using the `-u` extension. Thus, the collation type can be added to the initial locale identifier string that is passed into the {{jsxref("Intl/Locale/Locale", "Intl.Locale()")}} constructor. To add the collation type, first add the `-u` extension to the string. Next, add the `-co` extension to indicate that you are adding a collation type. Finally, add the collation type to the string.
```js
const locale = new Intl.Locale("zh-Hant-u-co-zhuyin");
console.log(locale.collation); // "zhuyin"
```
### Adding a collation type via the configuration object argument
The {{jsxref("Intl/Locale/Locale", "Intl.Locale()")}} constructor has an optional configuration object argument, which can contain any of several extension types, including collation types. Set the `collation` property of the configuration object to your desired collation type, and then pass it into the constructor.
```js
const locale = new Intl.Locale("zh-Hant", { collation: "zhuyin" });
console.log(locale.collation); // "zhuyin"
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Intl.Locale")}}
- [`Intl.Locale.prototype.getCollations()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Locale/getCollations)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/locale | data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/locale/getnumberingsystems/index.md | ---
title: Intl.Locale.prototype.getNumberingSystems()
slug: Web/JavaScript/Reference/Global_Objects/Intl/Locale/getNumberingSystems
page-type: javascript-instance-method
browser-compat: javascript.builtins.Intl.Locale.getNumberingSystems
---
{{JSRef}}
The **`getNumberingSystems()`** method of {{jsxref("Intl.Locale")}} instances returns a list of one or more unique [numbering system](https://en.wikipedia.org/wiki/Numeral_system) identifiers for this locale.
> **Note:** In some versions of some browsers, this method was implemented as an accessor property called `numberingSystems`. However, because it returns a new array on each access, it is now implemented as a method to prevent the situation of `locale.numberingSystems === locale.numberingSystems` returning `false`. Check the [browser compatibility table](#browser_compatibility) for details.
## Syntax
```js-nolint
getNumberingSystems()
```
### Parameters
None.
### Return value
An array of strings representing all numbering systems commonly used for the `Locale`, sorted in descending preference. If the `Locale` already has a [`numberingSystem`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Locale/numberingSystem), then the returned array contains that single value.
A table of the standard Unicode numeral systems can be seen below.
### Supported numbering system types
| Value | Description |
| -------- | -------------------------------------------------------------------------- |
| adlm | Adlam digits |
| ahom | Ahom digits |
| arab | Arabic-Indic digits |
| arabext | Extended Arabic-Indic digits |
| armn | Armenian upper case numerals — algorithmic |
| armnlow | Armenian lower case numerals — algorithmic |
| bali | Balinese digits |
| beng | Bengali digits |
| bhks | Bhaiksuki digits |
| brah | Brahmi digits |
| cakm | Chakma digits |
| cham | Cham digits |
| cyrl | Cyrillic numerals — algorithmic |
| deva | Devanagari digits |
| ethi | Ethiopic numerals — algorithmic |
| finance | Financial numerals — may be algorithmic |
| fullwide | Full width digits |
| geor | Georgian numerals — algorithmic |
| gong | Gunjala Gondi digits |
| gonm | Masaram Gondi digits |
| grek | Greek upper case numerals — algorithmic |
| greklow | Greek lower case numerals — algorithmic |
| gujr | Gujarati digits |
| guru | Gurmukhi digits |
| hanidays | Han-character day-of-month numbering for lunar/other traditional calendars |
| hanidec | Positional decimal system using Chinese number ideographs as digits |
| hans | Simplified Chinese numerals — algorithmic |
| hansfin | Simplified Chinese financial numerals — algorithmic |
| hant | Traditional Chinese numerals — algorithmic |
| hantfin | Traditional Chinese financial numerals — algorithmic |
| hebr | Hebrew numerals — algorithmic |
| hmng | Pahawh Hmong digits |
| hmnp | Nyiakeng Puachue Hmong digits |
| java | Javanese digits |
| jpan | Japanese numerals — algorithmic |
| jpanfin | Japanese financial numerals — algorithmic |
| jpanyear | Japanese first-year Gannen numbering for Japanese calendar |
| kali | Kayah Li digits |
| khmr | Khmer digits |
| knda | Kannada digits |
| lana | Tai Tham Hora (secular) digits |
| lanatham | Tai Tham (ecclesiastical) digits |
| laoo | Lao digits |
| latn | Latin digits |
| lepc | Lepcha digits |
| limb | Limbu digits |
| mathbold | Mathematical bold digits |
| mathdbl | Mathematical double-struck digits |
| mathmono | Mathematical monospace digits |
| mathsanb | Mathematical sans-serif bold digits |
| mathsans | Mathematical sans-serif digits |
| mlym | Malayalam digits |
| modi | Modi digits |
| mong | Mongolian digits |
| mroo | Mro digits |
| mtei | Meetei Mayek digits |
| mymr | Myanmar digits |
| mymrshan | Myanmar Shan digits |
| mymrtlng | Myanmar Tai Laing digits |
| native | Native digits |
| newa | Newa digits |
| nkoo | N'Ko digits |
| olck | Ol Chiki digits |
| orya | Oriya digits |
| osma | Osmanya digits |
| rohg | Hanifi Rohingya digits |
| roman | Roman upper case numerals — algorithmic |
| romanlow | Roman lowercase numerals — algorithmic |
| saur | Saurashtra digits |
| shrd | Sharada digits |
| sind | Khudawadi digits |
| sinh | Sinhala Lith digits |
| sora | Sora_Sompeng digits |
| sund | Sundanese digits |
| takr | Takri digits |
| talu | New Tai Lue digits |
| taml | Tamil numerals — algorithmic |
| tamldec | Modern Tamil decimal digits |
| telu | Telugu digits |
| thai | Thai digits |
| tirh | Tirhuta digits |
| tibt | Tibetan digits |
| traditio | Traditional numerals — may be algorithmic |
| vaii | Vai digits |
| wara | Warang Citi digits |
| wcho | Wancho digits |
## Examples
### Obtaining supported numbering systems
If the `Locale` object doesn't have a `numberingSystem` already, `getNumberingSystems()` lists all commonly-used numbering systems for the given `Locale`. For examples of explicitly setting a `numberingSystem`, see [`numberingSystem` examples](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Locale/numberingSystem#examples).
```js
const arEG = new Intl.Locale("ar-EG");
console.log(arEG.getNumberingSystems()); // ["arab"]
```
```js
const ja = new Intl.Locale("ja");
console.log(ja.getNumberingSystems()); // ["latn"]
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Intl.Locale")}}
- [`Intl.Locale.prototype.numberingSystem`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Locale/numberingSystem)
- [Details on the standard Unicode numeral systems](https://github.com/unicode-org/cldr/blob/main/common/supplemental/numberingSystems.xml)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/locale | data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/locale/numberingsystem/index.md | ---
title: Intl.Locale.prototype.numberingSystem
slug: Web/JavaScript/Reference/Global_Objects/Intl/Locale/numberingSystem
page-type: javascript-instance-accessor-property
browser-compat: javascript.builtins.Intl.Locale.numberingSystem
---
{{JSRef}}
The **`numberingSystem`** accessor property of {{jsxref("Intl.Locale")}} instances returns the [numeral system](https://en.wikipedia.org/wiki/Numeral_system) for this locale.
## Description
A numeral system is a system for expressing numbers. The `numberingSystem` property's value is set at construction time, either through the `nu` key of the locale identifier or through the `numberingSystem` option of the {{jsxref("Intl/Locale/Locale", "Intl.Locale()")}} constructor. The latter takes priority if they are both present; and if neither is present, the property has value `undefined`.
For a list of supported numbering system types, see [`Intl.Locale.prototype.getNumberingSystems()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Locale/getNumberingSystems#supported_numbering_system_types).
## Examples
Like other locale subtags, the numbering system type can be added to the {{jsxref("Intl.Locale")}} object via the locale string, or a configuration object argument to the constructor.
### Adding a numbering system via the locale string
In the [Unicode locale string spec](https://www.unicode.org/reports/tr35/), numbering system types are locale key "extension subtags". These subtags add additional data about the locale, and are added to locale identifiers by using the `-u` extension. Thus, the numbering system type can be added to the initial locale identifier string that is passed into the {{jsxref("Intl/Locale/Locale", "Intl.Locale()")}} constructor. To add the numbering system type, first add the `-u` extension key to the string. Next, add the `-nu` extension to indicate that you are adding a numbering system. Finally, add the numbering system type to the string.
```js
const locale = new Intl.Locale("fr-Latn-FR-u-nu-mong");
console.log(locale.numberingSystem); // "mong"
```
### Adding a numbering system via the configuration object argument
The {{jsxref("Intl/Locale/Locale", "Intl.Locale()")}} constructor has an optional configuration object argument, which can contain any of several extension types, including numbering system types. Set the `numberingSystem` property of the configuration object to your desired numbering system type, and then pass it into the constructor.
```js
const locale = new Intl.Locale("en-Latn-US", { numberingSystem: "latn" });
console.log(locale.numberingSystem); // "latn"
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Intl.Locale")}}
- [`Intl.Locale.prototype.getNumberingSystems()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Locale/getNumberingSystems)
- [Details on the standard Unicode numeral systems](https://github.com/unicode-org/cldr/blob/main/common/supplemental/numberingSystems.xml)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/locale | data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/locale/getcollations/index.md | ---
title: Intl.Locale.prototype.getCollations()
slug: Web/JavaScript/Reference/Global_Objects/Intl/Locale/getCollations
page-type: javascript-instance-method
browser-compat: javascript.builtins.Intl.Locale.getCollations
---
{{JSRef}}
The **`getCollations()`** method of {{jsxref("Intl.Locale")}} instances returns a list of one or more [collation types](https://www.unicode.org/reports/tr35/tr35-collation.html#CLDR_collation) for this locale.
> **Note:** In some versions of some browsers, this method was implemented as an accessor property called `collations`. However, because it returns a new array on each access, it is now implemented as a method to prevent the situation of `locale.collations === locale.collations` returning `false`. Check the [browser compatibility table](#browser_compatibility) for details.
## Syntax
```js-nolint
getCollations()
```
### Parameters
None.
### Return value
An array of strings representing all collation types commonly used for the `Locale`, sorted in alphabetical order, with the `standard` and `search` values always excluded. If the `Locale` already has a [`collation`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Locale/collation), then the returned array contains that single value.
Below is a list of the supported collation types, adapted from the [Unicode collation specification](https://github.com/unicode-org/cldr/blob/2dd06669d833823e26872f249aa304bc9d9d2a90/common/bcp47/collation.xml).
### Supported collation types
- `big5han`
- : Pinyin ordering for Latin, big5 charset ordering for CJK characters (for Chinese)
> **Warning:** The `big5han` collation type is deprecated, not available in Firefox, Chrome or Edge.
- `compat`
- : A previous version of the ordering, for compatibility (for Arabic)
- `dict`
- : Dictionary style ordering (for Sinhala)
- `direct`
- : Binary code point order
> **Warning:** The `direct` collation type has been deprecated. Do not use.
- `ducet`
- : The default Unicode collation element table order
> **Warning:** The `ducet` collation type is not available to the Web. Use the `und` locale without a collation type specifier instead. `und` is the collation that is the closest to `ducet`.
- `emoji`
- : Recommended ordering for emoji characters (for the `und` locale)
- `eor`
- : European ordering rules (for the `und` locale)
- `gb2312`
- : Pinyin ordering for Latin, gb2312han charset ordering for CJK characters (for Chinese)
> **Warning:** The `gb2312` collation type is deprecated, not available in Firefox, Chrome or Edge.
- `phonebk`
- : Phonebook style ordering (for German)
- `phonetic`
- : Phonetic ordering (sorting based on pronunciation; for Lingala)
- `pinyin`
- : Pinyin ordering for Latin and for CJK characters (for Chinese)
- `reformed`
- : Reformed ordering (formerly for Swedish)
> **Warning:** Do not use explicitly. This is the old name for the default ordering for Swedish [whose collation naming used to differ from other languages](https://unicode-org.atlassian.net/browse/CLDR-15603). Since this was the default, request `sv` instead of requesting `sv-u-co-reformed`.
- `search`
- : Special collation type for string search
> **Warning:** Do not use as a collation type, since in [`Intl.Collator`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator), this collation is activated via the `"search"` value for the `usage` option. There is currently no API for substring search, so this is currently only good for filtering a list of strings by trying a full-string match of the key against each list item.
- `searchjl`
- : Special collation type for Korean initial consonant search
> **Warning:** This collation is not for sorting, even though it is made available through [`Intl.Collator`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator) instantiated with usage `"sort"` as opposed to usage `"search"`.
- `standard`
- : Default ordering for each language, except Chinese (and, previously, Swedish)
> **Warning:** Do not use explicitly. In general, it's unnecessary to specify this explicitly and specifying this for Swedish is problematic due to the different meaning for Swedish in the past.
- `stroke`
- : Pinyin ordering for Latin, stroke order for CJK characters (for Chinese)
- `trad`
- : Traditional style ordering (such as in Spanish)
- `unihan`
- : Radical-stroke ordering for Han characters (for Chinese, Japanese, and Korean). Pinyin ordering for Latin in the case of Chinese.
> **Note:** The `unihan` collation type is not available in Chrome or Edge.
- `zhuyin`
- : Pinyin ordering for Latin, zhuyin order for Bopomofo and CJK characters (for Chinese)
## Examples
### Obtaining supported collation types
If the `Locale` object doesn't have a `collation` already, `getCollations()` lists all commonly-used collation types for the given `Locale`. For examples of explicitly setting a `collation`, see [`collation` examples](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Locale/collation#examples).
```js
const locale = new Intl.Locale("zh");
console.log(locale.getCollations()); // ["pinyin", "stroke", "zhuyin", "emoji", "eor"]
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Intl.Locale")}}
- [`Intl.Locale.prototype.collation`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Locale/collation)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/locale | data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/locale/gettextinfo/index.md | ---
title: Intl.Locale.prototype.getTextInfo()
slug: Web/JavaScript/Reference/Global_Objects/Intl/Locale/getTextInfo
page-type: javascript-instance-method
browser-compat: javascript.builtins.Intl.Locale.getTextInfo
---
{{JSRef}}
The **`getTextInfo()`** method of {{jsxref("Intl.Locale")}} instances returns the ordering of characters indicated by either `ltr` (left-to-right) or by `rtl` (right-to-left) for this locale.
> **Note:** In some versions of some browsers, this method was implemented as an accessor property called `textInfo`. However, because it returns a new object on each access, it is now implemented as a method to prevent the situation of `locale.textInfo === locale.textInfo` returning `false`. Check the [browser compatibility table](#browser_compatibility) for details.
## Syntax
```js-nolint
getTextInfo()
```
### Parameters
None.
### Return value
An object representing text typesetting information associated with the Locale data specified in [UTS 35's Layouts Elements](https://www.unicode.org/reports/tr35/tr35-general.html#Layout_Elements). It has the following properties:
- `direction`
- : A string indicating the direction of text for the locale. Can be either `"ltr"` (left-to-right) or `"rtl"` (right-to-left).
## Examples
### Obtaining text info
Return the supported text directions for a given `Locale`.
```js
const ar = new Intl.Locale("ar");
console.log(ar.getTextInfo()); // { direction: "rtl" }
console.log(ar.getTextInfo().direction); // "rtl"
```
```js
const es = new Intl.Locale("es");
console.log(es.getTextInfo()); // { direction: "ltr" }
console.log(es.getTextInfo().direction); // "ltr"
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Intl.Locale")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/locale | data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/locale/locale/index.md | ---
title: Intl.Locale() constructor
slug: Web/JavaScript/Reference/Global_Objects/Intl/Locale/Locale
page-type: javascript-constructor
browser-compat: javascript.builtins.Intl.Locale.Locale
---
{{JSRef}}
The **`Intl.Locale()`** constructor creates {{jsxref("Intl.Locale")}} objects.
{{EmbedInteractiveExample("pages/js/intl-locale.html")}}
## Syntax
```js-nolint
new Intl.Locale(tag)
new Intl.Locale(tag, options)
```
> **Note:** `Intl.Locale()` can only be constructed with [`new`](/en-US/docs/Web/JavaScript/Reference/Operators/new). Attempting to call it without `new` throws a {{jsxref("TypeError")}}.
### Parameters
- `tag`
- : The Unicode locale identifier string. For the syntax of locale identifier strings, see the [Intl main page](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#locales_argument). Note that the `Intl.Locale` constructor, unlike most other `Intl` constructors, does not accept an array of locales or `undefined`.
- `options`
- : An object that contains configuration for the Locale. Option values here take priority over extension keys in the locale identifier. Possible properties are:
- `language`
- : The language. Any syntactically valid string following the [`unicode_language_subtag`](https://unicode.org/reports/tr35/#unicode_language_subtag) grammar (2–3 or 5–8 letters) is accepted, but the implementation only recognizes certain kinds.
- `script`
- : The script. Any syntactically valid string following the [`unicode_script_subtag`](https://unicode.org/reports/tr35/#unicode_script_subtag) grammar (4 letters) is accepted, but the implementation only recognizes certain kinds.
- `region`
- : The region. Any syntactically valid string following the [`unicode_region_subtag`](https://unicode.org/reports/tr35/#unicode_region_subtag) grammar (either 2 letters or 3 digits) is accepted, but the implementation only recognizes certain kinds.
- `calendar`
- : The calendar. Any syntactically valid string following the [`type`](https://unicode.org/reports/tr35/#Unicode_locale_identifier) grammar (one or more segments of 3–8 alphanumerals, joined by hyphens) is accepted, but the implementation only recognizes certain kinds, which are listed in [`Intl.Locale.prototype.getCalendars`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Locale/getCalendars#supported_calendar_types).
- `collation`
- : The collation. Any syntactically valid string following the `type` grammar is accepted, but the implementation only recognizes certain kinds, which are listed in [`Intl.Locale.prototype.getCollations`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Locale/getCollations#supported_collation_types).
- `numberingSystem`
- : The numbering system. Any syntactically valid string following the `type` grammar is accepted, but the implementation only recognizes certain kinds, which are listed in [`Intl.Locale.prototype.getNumberingSystems`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Locale/getNumberingSystems#supported_numbering_systems).
- `caseFirst`
- : The case-first sort option. Possible values are `"upper"`, `"lower"`, or `"false"`.
- `hourCycle`
- : The hour cycle. Possible values are `"h23"`, `"h12"`, `"h11"`, or the practically unused `"h24"`, which are explained in [`Intl.Locale.prototype.getHourCycles`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Locale/getHourCycles#supported_hour_cycle_types)
- `numeric`
- : The numeric sort option. A boolean.
## Examples
### Basic usage
At its very simplest, the {{jsxref("Intl/Locale/Locale", "Intl.Locale()")}} constructor takes
a locale identifier string as its argument:
```js
const us = new Intl.Locale("en-US");
```
### Using the Locale constructor with an options object
The constructor also takes an optional configuration object argument, which can contain
any of several extension types. For example, set the
[`hourCycle`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Locale/hourCycle)
property of the configuration object to your desired hour cycle type, and then pass it
into the constructor:
```js
const locale = new Intl.Locale("en-US", { hourCycle: "h12" });
console.log(locale.hourCycle); // "h12"
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `Intl.Locale` in FormatJS](https://formatjs.io/docs/polyfills/intl-locale/)
- {{jsxref("Intl.Collator")}}
- [Canonical Unicode Locale Identifiers](https://www.unicode.org/reports/tr35/#Canonical_Unicode_Locale_Identifiers) in the Unicode locale data markup language spec
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/locale | data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/locale/getcalendars/index.md | ---
title: Intl.Locale.prototype.getCalendars()
slug: Web/JavaScript/Reference/Global_Objects/Intl/Locale/getCalendars
page-type: javascript-instance-method
browser-compat: javascript.builtins.Intl.Locale.getCalendars
---
{{JSRef}}
The **`getCalendars()`** method of {{jsxref("Intl.Locale")}} instances returns a list of one or more unique calendar identifiers for this locale.
> **Note:** In some versions of some browsers, this method was implemented as an accessor property called `calendars`. However, because it returns a new array on each access, it is now implemented as a method to prevent the situation of `locale.calendars === locale.calendars` returning `false`. Check the [browser compatibility table](#browser_compatibility) for details.
## Syntax
```js-nolint
getCalendars()
```
### Parameters
None.
### Return value
An array of strings representing all calendars commonly used for the `Locale`, sorted in descending preference. If the `Locale` already has a [`calendar`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Locale/calendar), then the returned array contains that single value.
Below is a list of the supported calendar era types.
### Supported calendar types
- `buddhist`
- : Thai Buddhist calendar
- `chinese`
- : Traditional Chinese calendar
- `coptic`
- : Coptic calendar
- `dangi`
- : Traditional Korean calendar
- `ethioaa`
- : Ethiopic calendar, Amete Alem (epoch approx. 5493 B.C.E)
- `ethiopic`
- : Ethiopic calendar, Amete Mihret (epoch approx, 8 C.E.)
- `gregory`
- : Gregorian calendar
- `hebrew`
- : Traditional Hebrew calendar
- `indian`
- : Indian calendar
- `islamic`
- : Islamic calendar
- `islamic-umalqura`
- : Islamic calendar, Umm al-Qura
- `islamic-tbla`
- : Islamic calendar, tabular (intercalary years [2,5,7,10,13,16,18,21,24,26,29] - astronomical epoch)
- `islamic-civil`
- : Islamic calendar, tabular (intercalary years [2,5,7,10,13,16,18,21,24,26,29] - civil epoch)
- `islamic-rgsa`
- : Islamic calendar, Saudi Arabia sighting
- `iso8601`
- : ISO calendar (Gregorian calendar using the ISO 8601 calendar week rules)
- `japanese`
- : Japanese Imperial calendar
- `persian`
- : Persian calendar
- `roc`
- : Civil (algorithmic) Arabic calendar
- `islamicc`
- : Civil (algorithmic) Arabic calendar
> **Warning:** The `islamicc` calendar key has been deprecated. Please use `islamic-civil`.
## Examples
### Obtaining supported calendars
If the `Locale` object doesn't have a `calendar` already, `getCalendars()` lists all commonly-used calendars for the given `Locale`. For examples of explicitly setting a `calendar`, see [`calendar` examples](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Locale/calendar#examples).
```js
const arEG = new Intl.Locale("ar-EG");
console.log(arEG.getCalendars()); // ["gregory", "coptic", "islamic", "islamic-civil", "islamic-tbla"]
```
```js
const jaJP = new Intl.Locale("ja-JP");
console.log(jaJP.getCalendars()); // ["gregory", "japanese"]
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Intl.Locale")}}
- [`Intl.Locale.prototype.calendar`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Locale/calendar)
- [Unicode Calendar Identifier](https://www.unicode.org/reports/tr35/#UnicodeCalendarIdentifier) in the Unicode locale data markup language spec
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/locale | data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/locale/getweekinfo/index.md | ---
title: Intl.Locale.prototype.getWeekInfo()
slug: Web/JavaScript/Reference/Global_Objects/Intl/Locale/getWeekInfo
page-type: javascript-instance-method
browser-compat: javascript.builtins.Intl.Locale.getWeekInfo
---
{{JSRef}}
The **`getWeekInfo()`** method of {{jsxref("Intl.Locale")}} instances returns a `weekInfo` object with the properties `firstDay`, `weekend` and `minimalDays` for this locale.
> **Note:** In some versions of some browsers, this method was implemented as an accessor property called `weekInfo`. However, because it returns a new object on each access, it is now implemented as a method to prevent the situation of `locale.weekInfo === locale.weekInfo` returning `false`. Check the [browser compatibility table](#browser_compatibility) for details.
## Syntax
```js-nolint
getWeekInfo()
```
### Parameters
None.
### Return value
An object representing week information associated with the Locale data specified in [UTS 35's Week Elements](https://www.unicode.org/reports/tr35/tr35-dates.html#Date_Patterns_Week_Elements). It has the following properties:
- `firstDay`
- : An integer indicating the first day of the week for the locale. Can be either `1` (Monday) or `7` (Sunday).
- `weekend`
- : An array of integers indicating the weekend days for the locale, where `1` is Monday and `7` is Sunday.
- `minimalDays`
- : An integer between 1 and 7 indicating the minimal days required in the first week of a month or year, for calendar purposes.
## Examples
### Obtaining the Week Information
Return the week information for a given `Locale`.
```js
const he = new Intl.Locale("he");
console.log(he.getWeekInfo()); // { firstDay: 7, weekend: [5, 6], minimalDays: 1 }
const af = new Intl.Locale("af");
console.log(af.getWeekInfo()); // { firstDay: 7, weekend: [6, 7], minimalDays: 1 }
const enGB = new Intl.Locale("en-GB");
console.log(enGB.getWeekInfo()); // { firstDay: 1, weekend: [6, 7], minimalDays: 4 }
const msBN = new Intl.Locale("ms-BN");
console.log(msBN.getWeekInfo()); // { firstDay: 7, weekend: [5, 7], minimalDays: 1 }
// Brunei weekend is Friday and Sunday but not Saturday
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Intl.Locale")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/locale | data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/locale/script/index.md | ---
title: Intl.Locale.prototype.script
slug: Web/JavaScript/Reference/Global_Objects/Intl/Locale/script
page-type: javascript-instance-accessor-property
browser-compat: javascript.builtins.Intl.Locale.script
---
{{JSRef}}
The **`script`** accessor property of {{jsxref("Intl.Locale")}} instances returns the script used for writing the particular language used in this locale.
## Description
A script, sometimes called writing system, is one of the core attributes of a locale. It indicates the set of symbols, or glyphs, that are used to write a particular language. For instance, the script associated with English is Latin, whereas the script typically associated with Korean is Hangul. In many cases, denoting a script is not strictly necessary, since the language (which is necessary) is only written in a single script. There are exceptions to this rule, however, and it is important to indicate the script whenever possible, in order to have a complete Unicode language identifier.
## Examples
### Setting the script in the locale identifier string argument
The script is the second part of a valid Unicode language identifier string, and can be set by adding it to the locale identifier string that is passed into the {{jsxref("Intl/Locale/Locale", "Intl.Locale()")}} constructor. Note that the script is not a required part of a locale identifier.
```js
const locale = new Intl.Locale("en-Latn-US");
console.log(locale.script); // Prints "Latn"
```
### Setting the script via the configuration object
The {{jsxref("Intl/Locale/Locale", "Intl.Locale()")}} constructor takes a configuration object, which can be used to set the script subtag and property.
```js
const locale = new Intl.Locale("fr-FR", { script: "Latn" });
console.log(locale.script); // Prints "Latn"
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Intl.Locale")}}
- [Unicode script subtag](https://www.unicode.org/reports/tr35/#unicode_script_subtag_validity) in the Unicode locale data markup language spec
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/locale | data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/locale/gethourcycles/index.md | ---
title: Intl.Locale.prototype.getHourCycles()
slug: Web/JavaScript/Reference/Global_Objects/Intl/Locale/getHourCycles
page-type: javascript-instance-method
browser-compat: javascript.builtins.Intl.Locale.getHourCycles
---
{{JSRef}}
The **`getHourCycles()`** method of {{jsxref("Intl.Locale")}} instances returns a list of one or more unique hour cycle identifiers for this locale.
> **Note:** In some versions of some browsers, this method was implemented as an accessor property called `hourCycles`. However, because it returns a new array on each access, it is now implemented as a method to prevent the situation of `locale.hourCycles === locale.hourCycles` returning `false`. Check the [browser compatibility table](#browser_compatibility) for details.
## Syntax
```js-nolint
getHourCycles()
```
### Parameters
None.
### Return value
An array of strings representing all hour cycle types commonly used for the `Locale`, sorted in descending preference. If the `Locale` already has an [`hourCycle`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Locale/hourCycle), then the returned array contains that single value.
Below is a list of supported hour cycle types.
### Supported hour cycle types
- `h12`
- : Hour system using 1–12; corresponds to 'h' in patterns. The 12 hour clock, with midnight starting at 12:00 am. As used, for example, in the United States.
- `h23`
- : Hour system using 0–23; corresponds to 'H' in patterns. The 24 hour clock, with midnight starting at 0:00.
- `h11`
- : Hour system using 0–11; corresponds to 'K' in patterns. The 12 hour clock, with midnight starting at 0:00 am. Mostly used in Japan.
- `h24`
- : Hour system using 1–24; corresponds to 'k' in pattern. The 24 hour clock, with midnight starting at 24:00. Not used anywhere.
## Examples
### Obtaining supported hour cycles
If the `Locale` object doesn't have a `hourCycle` already, `getHourCycles()` lists all commonly-used collation types for the given `Locale`. For examples of explicitly setting a `hourCycle`, see [`hourCycle` examples](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Locale/hourCycle#examples).
```js
const arEG = new Intl.Locale("ar-EG");
console.log(arEG.getHourCycles()); // ["h12"]
```
```js
const jaJP = new Intl.Locale("ja-JP");
console.log(jaJP.getHourCycles()); // ["h23"]
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Intl.Locale")}}
- [`Intl.Locale.prototype.hourCycle`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Locale/hourCycle)
- [Unicode Hour Cycle Identifier](https://www.unicode.org/reports/tr35/#UnicodeHourCycleIdentifier) in the Unicode locale data markup language spec
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/locale | data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/locale/gettimezones/index.md | ---
title: Intl.Locale.prototype.getTimeZones()
slug: Web/JavaScript/Reference/Global_Objects/Intl/Locale/getTimeZones
page-type: javascript-instance-method
browser-compat: javascript.builtins.Intl.Locale.getTimeZones
---
{{JSRef}}
The **`getTimeZones()`** method of {{jsxref("Intl.Locale")}} instances returns a list of supported time zones for this locale.
> **Note:** In some versions of some browsers, this method was implemented as an accessor property called `timeZones`. However, because it returns a new array on each access, it is now implemented as a method to prevent the situation of `locale.timeZones === locale.timeZones` returning `false`. Check the [browser compatibility table](#browser_compatibility) for details.
## Syntax
```js-nolint
getTimeZones()
```
### Parameters
None.
### Return value
An array of strings representing supported time zones for the associated `Locale`, where each value is an [IANA time zone canonical name](https://en.wikipedia.org/wiki/Daylight_saving_time#IANA_time_zone_database), sorted in alphabetical order. If the locale identifier does not contain a region subtag, the returned value is `undefined`.
## Examples
### Obtaining supported time zones
List supported time zones for a given `Locale`.
```js
const arEG = new Intl.Locale("ar-EG");
console.log(arEG.getTimeZones()); // ["Africa/Cairo"]
```
```js
const jaJP = new Intl.Locale("ja-JP");
console.log(jaJP.getTimeZones()); // ["Asia/Tokyo"]
```
```js
const ar = new Intl.Locale("ar");
console.log(ar.getTimeZones()); // undefined
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Intl.Locale")}}
- [IANA time zone database](https://en.wikipedia.org/wiki/Daylight_saving_time#IANA_time_zone_database) on Wikipedia
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/locale | data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/locale/numeric/index.md | ---
title: Intl.Locale.prototype.numeric
slug: Web/JavaScript/Reference/Global_Objects/Intl/Locale/numeric
page-type: javascript-instance-accessor-property
browser-compat: javascript.builtins.Intl.Locale.numeric
---
{{JSRef}}
The **`numeric`** accessor property of {{jsxref("Intl.Locale")}} instances returns whether this locale has special collation handling for numeric characters.
## Description
Like {{jsxref("Intl/Locale/caseFirst", "caseFirst")}}, `numeric` represents a modification to the collation rules utilized by the locale. `numeric` is a boolean value, which means that it can be either `true` or `false`. If `numeric` is set to `false`, there will be no special handling of numeric values in strings. If `numeric` is set to `true`, then the locale will take numeric characters into account when collating strings. This special numeric handling means that sequences of decimal digits will be compared as numbers. For example, the string "A-21" will be considered less than "A-123".
## Examples
### Setting the numeric value via the locale string
In the [Unicode locale string spec](https://www.unicode.org/reports/tr35/), the values that `numeric` represents correspond to the key `kn`. `kn` is considered a locale string "extension subtag". These subtags add additional data about the locale, and are added to locale identifiers by using the `-u` extension key. Thus, the `numeric` value can be added to the initial locale identifier string that is passed into the {{jsxref("Intl/Locale/Locale", "Intl.Locale()")}} constructor. To set the `numeric` value, first add the `-u` extension key to the string. Next, add the `-kn` extension key to indicate that you are adding a value for `numeric`. Finally, add the `numeric` value to the string. If you want to set `numeric` to `true`, adding the `kn` key will suffice. To set the value to `false`, you must specify in by adding `"false"` after the `kn` key.
```js
const locale = new Intl.Locale("fr-Latn-FR-u-kn-false");
console.log(locale.numeric); // Prints "false"
```
### Setting the numeric value via the configuration object argument
The {{jsxref("Intl/Locale/Locale", "Intl.Locale()")}} constructor has an optional configuration object argument, which can be used to pass extension types. Set the `numeric` property of the configuration object to your desired `numeric` value and pass it into the constructor.
```js
const locale = new Intl.Locale("en-Latn-US", { numeric: true });
console.log(locale.numeric); // Prints "true"
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Intl.Locale")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/locale | data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/locale/casefirst/index.md | ---
title: Intl.Locale.prototype.caseFirst
slug: Web/JavaScript/Reference/Global_Objects/Intl/Locale/caseFirst
page-type: javascript-instance-accessor-property
browser-compat: javascript.builtins.Intl.Locale.caseFirst
---
{{JSRef}}
The **`caseFirst`** accessor property of {{jsxref("Intl.Locale")}} instances returns whether case is taken into account for this locale's collation rules.
## Description
A locale's collation rules are used to determine how strings are ordered in that locale. Certain locales use a character's case (UPPERCASE or lowercase) in the collation process. This additional rule can be expressed in a {{jsxref("Intl.Locale")}} object's `caseFirst` property.
There are 3 values that the `caseFirst` property can have, outlined in the table below.
### `caseFirst` values
| Value | Description |
| ------- | ------------------------------------------ |
| `upper` | Upper case to be sorted before lower case. |
| `lower` | Lower case to be sorted before upper case. |
| `false` | No special case ordering. |
## Examples
### Setting the caseFirst value via the locale string
In the [Unicode locale string spec](https://www.unicode.org/reports/tr35/), the values that `caseFirst` represents correspond to the key `kf`. `kf` is treated as a locale string "extension subtag". These subtags add additional data about the locale, and are added to locale identifiers by using the `-u` extension key. Thus, the `caseFirst` value can be added to the initial locale identifier string that is passed into the `Locale` constructor. To add the `caseFirst` value, first add the `-u` extension key to the string. Next, add the `-kf` extension key to indicate that you are adding a value for `caseFirst`. Finally, add the `caseFirst` value to the string.
```js
const locale = new Intl.Locale("fr-Latn-FR-u-kf-upper");
console.log(locale.caseFirst); // Prints "upper"
```
### Setting the caseFirst value via the configuration object argument
The {{jsxref("Intl/Locale/Locale", "Intl.Locale()")}} constructor has an optional configuration object argument, which can be used to pass extension types. Set the `caseFirst` property of the configuration object to your desired `caseFirst` value, and then pass it into the constructor.
```js
const locale = new Intl.Locale("en-Latn-US", { caseFirst: "lower" });
console.log(locale.caseFirst); // Prints "lower"
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Intl.Locale")}}
- [Unicode case first collation spec](https://github.com/unicode-org/cldr/blob/main/common/bcp47/collation.xml#L49)
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl | data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/datetimeformat/index.md | ---
title: Intl.DateTimeFormat
slug: Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat
page-type: javascript-class
browser-compat: javascript.builtins.Intl.DateTimeFormat
---
{{JSRef}}
The **`Intl.DateTimeFormat`** object enables language-sensitive date and time formatting.
{{EmbedInteractiveExample("pages/js/intl-datetimeformat.html", "taller")}}
## Constructor
- {{jsxref("Intl/DateTimeFormat/DateTimeFormat", "Intl.DateTimeFormat()")}}
- : Creates a new `Intl.DateTimeFormat` object.
## Static methods
- {{jsxref("Intl/DateTimeFormat/supportedLocalesOf", "Intl.DateTimeFormat.supportedLocalesOf()")}}
- : Returns an array containing those of the provided locales that are supported without having to fall back to the runtime's default locale.
## Instance properties
These properties are defined on `Intl.DateTimeFormat.prototype` and shared by all `Intl.DateTimeFormat` instances.
- {{jsxref("Object/constructor", "Intl.DateTimeFormat.prototype.constructor")}}
- : The constructor function that created the instance object. For `Intl.DateTimeFormat` instances, the initial value is the {{jsxref("Intl/DateTimeFormat/DateTimeFormat", "Intl.DateTimeFormat")}} constructor.
- `Intl.DateTimeFormat.prototype[@@toStringTag]`
- : The initial value of the [`@@toStringTag`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/toStringTag) property is the string `"Intl.DateTimeFormat"`. This property is used in {{jsxref("Object.prototype.toString()")}}.
## Instance methods
- {{jsxref("Intl/DateTimeFormat/format", "Intl.DateTimeFormat.prototype.format()")}}
- : Getter function that formats a date according to the locale and formatting options of this `DateTimeFormat` object.
- {{jsxref("Intl/DateTimeFormat/formatRange", "Intl.DateTimeFormat.prototype.formatRange()")}}
- : This method receives two [Dates](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) and formats the date range in the most concise way based on the locale and options provided when instantiating `DateTimeFormat`.
- {{jsxref("Intl/DateTimeFormat/formatRangeToParts", "Intl.DateTimeFormat.prototype.formatRangeToParts()")}}
- : This method receives two [Dates](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) and returns an Array of objects containing the locale-specific tokens representing each part of the formatted date range.
- {{jsxref("Intl/DateTimeFormat/formatToParts", "Intl.DateTimeFormat.prototype.formatToParts()")}}
- : Returns an {{jsxref("Array")}} of objects representing the date string in parts that can be used for custom locale-aware formatting.
- {{jsxref("Intl/DateTimeFormat/resolvedOptions", "Intl.DateTimeFormat.prototype.resolvedOptions()")}}
- : Returns a new object with properties reflecting the locale and formatting options computed during initialization of the object.
## Examples
### Using DateTimeFormat
In basic use without specifying a locale, `DateTimeFormat` uses the default locale and default options.
```js
const date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));
// toLocaleString without arguments depends on the implementation,
// the default locale, and the default time zone
console.log(new Intl.DateTimeFormat().format(date));
// "12/19/2012" if run with en-US locale (language) and time zone America/Los_Angeles (UTC-0800)
```
### Using locales
This example shows some of the variations in localized date and time formats. In order to get the format of the language used in the user interface of your application, make sure to specify that language (and possibly some fallback languages) using the `locales` argument:
```js
const date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));
// Results below use the time zone of America/Los_Angeles (UTC-0800, Pacific Standard Time)
// US English uses month-day-year order
console.log(new Intl.DateTimeFormat("en-US").format(date));
// "12/19/2012"
// British English uses day-month-year order
console.log(new Intl.DateTimeFormat("en-GB").format(date));
// "19/12/2012"
// Korean uses year-month-day order
console.log(new Intl.DateTimeFormat("ko-KR").format(date));
// "2012. 12. 19."
// Arabic in most Arabic speaking countries uses real Arabic digits
console.log(new Intl.DateTimeFormat("ar-EG").format(date));
// "١٩/١٢/٢٠١٢"
// for Japanese, applications may want to use the Japanese calendar,
// where 2012 was the year 24 of the Heisei era
console.log(new Intl.DateTimeFormat("ja-JP-u-ca-japanese").format(date));
// "24/12/19"
// when requesting a language that may not be supported, such as
// Balinese, include a fallback language, in this case Indonesian
console.log(new Intl.DateTimeFormat(["ban", "id"]).format(date));
// "19/12/2012"
```
### Using options
The date and time formats can be customized using the `options` argument:
```js
const date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0, 200));
// request a weekday along with a long date
let options = {
weekday: "long",
year: "numeric",
month: "long",
day: "numeric",
};
console.log(new Intl.DateTimeFormat("de-DE", options).format(date));
// "Donnerstag, 20. Dezember 2012"
// an application may want to use UTC and make that visible
options.timeZone = "UTC";
options.timeZoneName = "short";
console.log(new Intl.DateTimeFormat("en-US", options).format(date));
// "Thursday, December 20, 2012, GMT"
// sometimes you want to be more precise
options = {
hour: "numeric",
minute: "numeric",
second: "numeric",
timeZone: "Australia/Sydney",
timeZoneName: "short",
};
console.log(new Intl.DateTimeFormat("en-AU", options).format(date));
// "2:00:00 pm AEDT"
// sometimes you want to be very precise
options.fractionalSecondDigits = 3; //number digits for fraction-of-seconds
console.log(new Intl.DateTimeFormat("en-AU", options).format(date));
// "2:00:00.200 pm AEDT"
// sometimes even the US needs 24-hour time
options = {
year: "numeric",
month: "numeric",
day: "numeric",
hour: "numeric",
minute: "numeric",
second: "numeric",
hour12: false,
timeZone: "America/Los_Angeles",
};
console.log(new Intl.DateTimeFormat("en-US", options).format(date));
// "12/19/2012, 19:00:00"
// to specify options but use the browser's default locale, use undefined
console.log(new Intl.DateTimeFormat(undefined, options).format(date));
// "12/19/2012, 19:00:00"
// sometimes it's helpful to include the period of the day
options = { hour: "numeric", dayPeriod: "short" };
console.log(new Intl.DateTimeFormat("en-US", options).format(date));
// 10 at night
```
The used calendar and numbering formats can also be set independently via `options` arguments:
```js
const options = { calendar: "chinese", numberingSystem: "arab" };
const dateFormat = new Intl.DateTimeFormat(undefined, options);
const usedOptions = dateFormat.resolvedOptions();
console.log(usedOptions.calendar);
// "chinese"
console.log(usedOptions.numberingSystem);
// "arab"
console.log(usedOptions.timeZone);
// "America/New_York" (the users default timezone)
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `Intl.DateTimeFormat` in FormatJS](https://formatjs.io/docs/polyfills/intl-datetimeformat/)
- {{jsxref("Intl")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/datetimeformat | data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/datetimeformat/formatrange/index.md | ---
title: Intl.DateTimeFormat.prototype.formatRange()
slug: Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/formatRange
page-type: javascript-instance-method
browser-compat: javascript.builtins.Intl.DateTimeFormat.formatRange
---
{{JSRef}}
The **`formatRange()`** method of {{jsxref("Intl.DateTimeFormat")}} instances formats a
date range in the most concise way based on the locales and
options provided when instantiating this
`Intl.DateTimeFormat` object.
{{EmbedInteractiveExample("pages/js/intl-datetimeformat-prototype-formatrange.html", "taller")}}
## Syntax
```js-nolint
formatRange(startDate, endDate)
```
### Parameters
- `startDate`
- : A {{jsxref("Date")}} object representing the start of the date range.
- `endDate`
- : A {{jsxref("Date")}} object representing the end of the date range.
### Return value
A string representing the given date range formatted according to the locale and formatting options of this {{jsxref("Intl.DateTimeFormat")}} object.
## Examples
### Basic formatRange usage
This method receives two {{jsxref("Date")}}s and formats the date range in the most
concise way based on the `locale` and `options` provided when
instantiating {{jsxref("Intl.DateTimeFormat")}}.
```js
const date1 = new Date(Date.UTC(1906, 0, 10, 10, 0, 0)); // Wed, 10 Jan 1906 10:00:00 GMT
const date2 = new Date(Date.UTC(1906, 0, 10, 11, 0, 0)); // Wed, 10 Jan 1906 11:00:00 GMT
const date3 = new Date(Date.UTC(1906, 0, 20, 10, 0, 0)); // Sat, 20 Jan 1906 10:00:00 GMT
const fmt1 = new Intl.DateTimeFormat("en", {
year: "2-digit",
month: "numeric",
day: "numeric",
hour: "numeric",
minute: "numeric",
});
console.log(fmt1.format(date1)); // '1/10/06, 10:00 AM'
console.log(fmt1.formatRange(date1, date2)); // '1/10/06, 10:00 – 11:00 AM'
console.log(fmt1.formatRange(date1, date3)); // '1/10/06, 10:00 AM – 1/20/07, 10:00 AM'
const fmt2 = new Intl.DateTimeFormat("en", {
year: "numeric",
month: "short",
day: "numeric",
});
console.log(fmt2.format(date1)); // 'Jan 10, 1906'
console.log(fmt2.formatRange(date1, date2)); // 'Jan 10, 1906'
console.log(fmt2.formatRange(date1, date3)); // 'Jan 10 – 20, 1906'
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Intl.DateTimeFormat")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/datetimeformat | data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/datetimeformat/format/index.md | ---
title: Intl.DateTimeFormat.prototype.format()
slug: Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/format
page-type: javascript-instance-method
browser-compat: javascript.builtins.Intl.DateTimeFormat.format
---
{{JSRef}}
The **`format()`** method of {{jsxref("Intl.DateTimeFormat")}} instances formats a date according to the locale and formatting options of this `Intl.DateTimeFormat` object.
{{EmbedInteractiveExample("pages/js/intl-datetimeformat-prototype-format.html", "taller")}}
## Syntax
```js-nolint
format(date)
```
### Parameters
- `date`
- : The date to format.
### Return value
A string representing the given `date` formatted according to the locale and formatting options of this {{jsxref("Intl.DateTimeFormat")}} object.
## Examples
### Using format
Use the `format` getter function for formatting a single date, here for
Serbia:
```js
const options = {
weekday: "long",
year: "numeric",
month: "long",
day: "numeric",
};
const dateTimeFormat = new Intl.DateTimeFormat("sr-RS", options);
console.log(dateTimeFormat.format(new Date()));
// "недеља, 7. април 2013."
```
### Using format with map
Use the `format` getter function for formatting all dates in an array. Note
that the function is bound to the {{jsxref("Intl.DateTimeFormat")}}
from which it was obtained, so it can be passed directly to
{{jsxref("Array.prototype.map()")}}.
```js
const a = [new Date(2012, 8), new Date(2012, 11), new Date(2012, 3)];
const options = { year: "numeric", month: "long" };
const dateTimeFormat = new Intl.DateTimeFormat("pt-BR", options);
const formatted = a.map(dateTimeFormat.format);
console.log(formatted.join("; "));
// "setembro de 2012; dezembro de 2012; abril de 2012"
```
### Avoid comparing formatted date values to static values
Most of the time, the formatting returned by `format()` is consistent.
However, this might change in the future and isn't guaranteed for all the languages —
output variations are by design and allowed by the specification. Most notably, the IE
and Edge browsers insert bidirectional control characters around dates, so the output
text will flow properly when concatenated with other text.
For this reason you cannot expect to be able to compare the results of
`format()` to a static value:
```js example-bad
let d = new Date("2019-01-01T00:00:00.000000Z");
let formattedDate = Intl.DateTimeFormat(undefined, {
year: "numeric",
month: "numeric",
day: "numeric",
hour: "numeric",
minute: "numeric",
second: "numeric",
}).format(d);
"1.1.2019, 01:00:00" === formattedDate;
// true in Firefox and others
// false in IE and Edge
```
> **Note:** See also this [StackOverflow thread](https://stackoverflow.com/questions/25574963/ies-tolocalestring-has-strange-characters-in-results)
> for more details and examples.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Intl.DateTimeFormat")}}
- {{jsxref("Date.prototype.toLocaleString()")}}
- {{jsxref("Date.prototype.toLocaleDateString()")}}
- {{jsxref("Date.prototype.toLocaleTimeString()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/datetimeformat | data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/datetimeformat/resolvedoptions/index.md | ---
title: Intl.DateTimeFormat.prototype.resolvedOptions()
slug: Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/resolvedOptions
page-type: javascript-instance-method
browser-compat: javascript.builtins.Intl.DateTimeFormat.resolvedOptions
---
{{JSRef}}
The **`resolvedOptions()`** method of {{jsxref("Intl.DateTimeFormat")}} instances returns a new object with properties reflecting the locale and date and time formatting options computed during initialization of this `Intl.DateTimeFormat` object.
{{EmbedInteractiveExample("pages/js/intl-datetimeformat-prototype-resolvedoptions.html")}}
## Syntax
```js-nolint
resolvedOptions()
```
### Parameters
None.
### Return value
A new object with properties reflecting the locale and date and time formatting options
computed during the initialization of the given {{jsxref("Intl.DateTimeFormat")}} object.
## Description
The resulting object has the following properties:
- `locale`
- : The BCP 47 language tag for the locale actually used. If any Unicode extension
values were requested in the input BCP 47 language tag that led to this locale,
the key-value pairs that were requested and are supported for this locale are
included in `locale`.
- `calendar`
- : E.g. "gregory"
- `numberingSystem`
- : The values requested using the Unicode extension keys `"ca"` and
`"nu"` or filled in as default values.
- `timeZone`
- : The value provided for this property in the `options` argument;
defaults to the runtime's default time zone. Should never be `undefined`.
- `hour12`
- : The value provided for this property in the `options` argument or
filled in as a default.
- `weekday`, `era`, `year`, `month`, `day`, `hour`, `minute`, `second`, `timeZoneName`
- : The values resulting from format matching between the corresponding properties in
the `options` argument and the available combinations and
representations for date-time formatting in the selected locale. Some of these
properties may not be present, indicating that the corresponding components will
not be represented in formatted output.
## Examples
### Using the resolvedOptions method
```js
const germanFakeRegion = new Intl.DateTimeFormat("de-XX", { timeZone: "UTC" });
const usedOptions = germanFakeRegion.resolvedOptions();
usedOptions.locale; // "de"
usedOptions.calendar; // "gregory"
usedOptions.numberingSystem; // "latn"
usedOptions.timeZone; // "UTC"
usedOptions.month; // "numeric"
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Intl.DateTimeFormat")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/datetimeformat | data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/datetimeformat/formatrangetoparts/index.md | ---
title: Intl.DateTimeFormat.prototype.formatRangeToParts()
slug: Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/formatRangeToParts
page-type: javascript-instance-method
browser-compat: javascript.builtins.Intl.DateTimeFormat.formatRangeToParts
---
{{JSRef}}
The **`formatRangeToParts()`** method of {{jsxref("Intl.DateTimeFormat")}} instances returns an array of locale-specific tokens representing each part of the formatted date
range produced by this `Intl.DateTimeFormat` object.
{{EmbedInteractiveExample("pages/js/intl-datetimeformat-prototype-formatrangetoparts.html", "taller")}}
## Syntax
```js-nolint
formatRangeToParts(startDate, endDate)
```
## Examples
### Basic formatRangeToParts usage
This method receives two {{jsxref("Date")}}s and returns an {{jsxref("Array")}} of
objects containing the _locale-specific_ tokens representing each part of the formatted date range.
> **Note:** The return values shown in your locale may differ from those listed below.
```js
const date1 = new Date(Date.UTC(1906, 0, 10, 10, 0, 0)); // Wed, 10 Jan 1906 10:00:00 GMT
const date2 = new Date(Date.UTC(1906, 0, 10, 11, 0, 0)); // Wed, 10 Jan 1906 11:00:00 GMT
const fmt = new Intl.DateTimeFormat("en", {
hour: "numeric",
minute: "numeric",
});
console.log(fmt.formatRange(date1, date2)); // '10:00 – 11:00 AM'
fmt.formatRangeToParts(date1, date2);
// [
// { type: 'hour', value: '10', source: "startRange" },
// { type: 'literal', value: ':', source: "startRange" },
// { type: 'minute', value: '00', source: "startRange" },
// { type: 'literal', value: ' – ', source: "shared" },
// { type: 'hour', value: '11', source: "endRange" },
// { type: 'literal', value: ':', source: "endRange" },
// { type: 'minute', value: '00', source: "endRange" },
// { type: 'literal', value: ' ', source: "shared" },
// { type: 'dayPeriod', value: 'AM', source: "shared" }
// ]
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Intl/DateTimeFormat/formatRange", "Intl.DateTimeFormat.prototype.formatRange()")}}
- {{jsxref("Intl.DateTimeFormat")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/datetimeformat | data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/datetimeformat/formattoparts/index.md | ---
title: Intl.DateTimeFormat.prototype.formatToParts()
slug: Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/formatToParts
page-type: javascript-instance-method
browser-compat: javascript.builtins.Intl.DateTimeFormat.formatToParts
---
{{JSRef}}
The **`formatToParts()`** method of {{jsxref("Intl.DateTimeFormat")}} instances allows locale-aware formatting of strings produced by this `Intl.DateTimeFormat` object.
{{EmbedInteractiveExample("pages/js/intl-datetimeformat-prototype-formattoparts.html", "taller")}}
## Syntax
```js-nolint
formatToParts(date)
```
### Parameters
- `date` {{optional_inline}}
- : The date to format.
### Return value
An {{jsxref("Array")}} of objects containing the formatted date in parts.
## Description
The `formatToParts()` method is useful for custom formatting of date
strings. It returns an {{jsxref("Array")}} of objects containing the locale-specific
tokens from which it possible to build custom strings while preserving the
locale-specific parts. The structure the `formatToParts()` method returns,
looks like this:
```js
[
{ type: "day", value: "17" },
{ type: "weekday", value: "Monday" },
];
```
Possible types are the following:
- `day`
- : The string used for the day, for example `"17"`.
- `dayPeriod`
- : The string used for the day period, for example, `"AM"`,
`"PM"`, `"in the morning"`, or `"noon"`
- `era`
- : The string used for the era, for example `"BC"` or `"AD"`.
- `fractionalSecond`
- : The string used for the fractional seconds, for example `"0"` or `"00"` or `"000"`.
- `hour`
- : The string used for the hour, for example `"3"` or `"03"`.
- `literal`
- : The string used for separating date and time values, for example `"/"`,
`","`, `"o'clock"`, `"de"`, etc.
- `minute`
- : The string used for the minute, for example `"00"`.
- `month`
- : The string used for the month, for example `"12"`.
- `relatedYear`
- : The string used for the related 4-digit Gregorian year, in the event that the
calendar's representation would be a yearName instead of a year, for example `"2019"`.
- `second`
- : The string used for the second, for example `"07"` or `"42"`.
- `timeZone`
- : The string used for the name of the time zone, for example `"UTC"`. Default is the timezone of the current environment.
- `weekday`
- : The string used for the weekday, for example `"M"`, `"Monday"`, or `"Montag"`.
- `year`
- : The string used for the year, for example `"2012"` or `"96"`.
- `yearName`
- : The string used for the yearName in relevant contexts, for example `"geng-zi"`
## Examples
`DateTimeFormat` outputs localized, opaque strings that cannot be
manipulated directly:
```js
const date = Date.UTC(2012, 11, 17, 3, 0, 42);
const formatter = new Intl.DateTimeFormat("en-us", {
weekday: "long",
year: "numeric",
month: "numeric",
day: "numeric",
hour: "numeric",
minute: "numeric",
second: "numeric",
fractionalSecondDigits: 3,
hour12: true,
timeZone: "UTC",
});
formatter.format(date);
// "Monday, 12/17/2012, 3:00:42.000 AM"
```
However, in many User Interfaces there is a desire to customize the formatting of this
string. The `formatToParts` method enables locale-aware formatting of strings
produced by `DateTimeFormat` formatters by providing you the string in parts:
```js
formatter.formatToParts(date);
// return value:
[
{ type: "weekday", value: "Monday" },
{ type: "literal", value: ", " },
{ type: "month", value: "12" },
{ type: "literal", value: "/" },
{ type: "day", value: "17" },
{ type: "literal", value: "/" },
{ type: "year", value: "2012" },
{ type: "literal", value: ", " },
{ type: "hour", value: "3" },
{ type: "literal", value: ":" },
{ type: "minute", value: "00" },
{ type: "literal", value: ":" },
{ type: "second", value: "42" },
{ type: "fractionalSecond", value: "000" },
{ type: "literal", value: " " },
{ type: "dayPeriod", value: "AM" },
];
```
Now the information is available separately and it can be formatted and concatenated
again in a customized way. For example by using {{jsxref("Array.prototype.map()")}},
[arrow functions](/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions),
a [switch statement](/en-US/docs/Web/JavaScript/Reference/Statements/switch),
[template literals](/en-US/docs/Web/JavaScript/Reference/Template_literals),
and {{jsxref("Array.prototype.join()")}}.
```js
const dateString = formatter
.formatToParts(date)
.map(({ type, value }) => {
switch (type) {
case "dayPeriod":
return `<em>${value}</em>`;
default:
return value;
}
})
.join("");
```
This will emphasize the day period when using the `formatToParts()` method.
```js
console.log(formatter.format(date));
// "Monday, 12/17/2012, 3:00:42.000 AM"
console.log(dateString);
// "Monday, 12/17/2012, 3:00:42.000 <em>AM</em>"
```
### Named Years and Mixed calendars
In some cases, calendars use named years. Chinese and Tibetan calendars, for example,
use a 60-year [sexagenary cycle](https://en.wikipedia.org/wiki/Sexagenary_cycle) of named years.
These years are disambiguated by relationship to
corresponding years on the Gregorian calendar. When this is the case, the result of
`formatToParts()` will contain an entry for `relatedYear` when a
year would normally be present, containing the 4-digit Gregorian year, instead of an
entry for `year`. Setting an entry in the bag for `year` (with any
value) will yield both the and the `yearName` Gregorian
`relatedYear`:
```js
const opts = { year: "numeric", month: "numeric", day: "numeric" };
const df = new Intl.DateTimeFormat("zh-u-ca-chinese", opts);
df.formatToParts(Date.UTC(2012, 11, 17, 3, 0, 42));
// return value
[
{ type: "relatedYear", value: "2012" },
{ type: "literal", value: "年" },
{ type: "month", value: "十一月" },
{ type: "day", value: "4" },
];
```
If the `year` option is not set in the bag (to any value), the result will
include only the `relatedYear`:
```js
const df = new Intl.DateTimeFormat("zh-u-ca-chinese");
df.formatToParts(Date.UTC(2012, 11, 17, 3, 0, 42));
// return value
[
{ type: "relatedYear", value: "2012" },
{ type: "literal", value: "年" },
{ type: "month", value: "十一月" },
{ type: "day", value: "4" },
];
```
In cases where the `year` would be output, `.format()` may
commonly present these side-by-side:
```js
const df = new Intl.DateTimeFormat("zh-u-ca-chinese", { year: "numeric" });
df.format(Date.UTC(2012, 11, 17, 3, 0, 42)); // 2012壬辰年
```
This also makes it possible to mix locale and calendar in both `format`:
```js
const df = new Intl.DateTimeFormat("en-u-ca-chinese", { year: "numeric" });
const date = Date.UTC(2012, 11, 17, 3, 0, 42);
df.format(date); // 2012(ren-chen)
```
And `formatToParts`:
```js
const opts = { month: "numeric", day: "numeric", year: "numeric" };
const df = new Intl.DateTimeFormat("en-u-ca-chinese", opts);
const date = Date.UTC(2012, 11, 17, 3);
df.formatToParts(date);
// [
// { type: 'month', value: '11' },
// { type: 'literal', value: '/' },
// { type: 'day', value: '4' },
// { type: 'literal', value: '/' },
// { type: 'relatedYear', value: '2012' }
// ]
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Intl.DateTimeFormat")}}
- {{jsxref("Intl/DateTimeFormat/format", "Intl.DateTimeFormat.prototype.format()")}}
- {{jsxref("Date.prototype.toLocaleString()")}}
- {{jsxref("Date.prototype.toLocaleDateString()")}}
- {{jsxref("Date.prototype.toLocaleTimeString()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/datetimeformat | data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/datetimeformat/datetimeformat/index.md | ---
title: Intl.DateTimeFormat() constructor
slug: Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat
page-type: javascript-constructor
browser-compat: javascript.builtins.Intl.DateTimeFormat.DateTimeFormat
---
{{JSRef}}
The **`Intl.DateTimeFormat()`** constructor creates {{jsxref("Intl.DateTimeFormat")}} objects.
{{EmbedInteractiveExample("pages/js/intl-datetimeformat.html", "taller")}}
## Syntax
```js-nolint
new Intl.DateTimeFormat()
new Intl.DateTimeFormat(locales)
new Intl.DateTimeFormat(locales, options)
Intl.DateTimeFormat()
Intl.DateTimeFormat(locales)
Intl.DateTimeFormat(locales, options)
```
> **Note:** `Intl.DateTimeFormat()` can be called with or without [`new`](/en-US/docs/Web/JavaScript/Reference/Operators/new). Both create a new `Intl.DateTimeFormat` instance. However, there's a special behavior when it's called without `new` and the `this` value is another `Intl.DateTimeFormat` instance; see [Return value](#return_value).
### Parameters
- `locales` {{optional_inline}}
- : A string with a BCP 47 language tag or an {{jsxref("Intl.Locale")}} instance, or an array of such locale identifiers. For the general form and interpretation of the `locales` argument, see [the parameter description on the `Intl` main page](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#locales_argument).
The following Unicode extension key is allowed:
- `nu`
- : See [`numberingSystem`](#numberingsystem).
- `ca`
- : See [`calendar`](#calendar).
- `hc`
- : See [`hourCycle`](#hourcycle).
These keys can also be set with `options` (as listed below). When both are set, the `options` property takes precedence.
- `options` {{optional_inline}}
- : An object. For ease of reading, the property list is broken into sections based on their purposes, including [locale options](#locale_options), [date-time component options](#date-time_component_options), and [style shortcuts](#style_shortcuts).
#### Locale options
- `localeMatcher`
- : The locale matching algorithm to use. Possible values are `"lookup"` and `"best fit"`; the default is `"best fit"`. For information about this option, see [Locale identification and negotiation](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#locale_identification_and_negotiation).
- `calendar`
- : The calendar to use, such as `"chinese"`, `"gregory"`, `"persian"`, and so on. For a list of supported calendar types, see [`Intl.Locale.prototype.getCalendars()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Locale/getCalendars#supported_calendar_types). This option can also be set through the `ca` Unicode extension key; if both are provided, this `options` property takes precedence.
- `numberingSystem`
- : The numbering system to use for number formatting, such as `"arab"`, `"hans"`, `"mathsans"`, and so on. For a list of supported numbering system types, see [`Intl.Locale.prototype.getNumberingSystems()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Locale/getNumberingSystems#supported_numbering_system_types). This option can also be set through the `nu` Unicode extension key; if both are provided, this `options` property takes precedence.
- `hour12`
- : Whether to use 12-hour time (as opposed to 24-hour time). Possible values are `true` and `false`; the default is locale dependent. This option overrides the `hc` locale extension tag and/or the `hourCycle` option in case both are present. It sets `hourCycle` to `"h11"` or `"h12"` when `true`, and `"h23"` or `"h24"` when `false`, the exact choice depending on the locale — for example, if the locale most prefers `"h23"` but `hour12` is `true`, then the final hour cycle is `"h11"`.
- `hourCycle`
- : The hour cycle to use. Possible values are `"h11"`, `"h12"`, `"h23"`, and `"h24"`. This option can also be set through the `hc` Unicode extension key; if both are provided, this `options` property takes precedence.
- `timeZone`
- : The time zone to use. The only value implementations must recognize is `"UTC"`; the default is the runtime's default time zone. Implementations may also recognize the time zone names of the [IANA time zone database](https://www.iana.org/time-zones), such as `"Asia/Shanghai"`, `"Asia/Kolkata"`, `"America/New_York"`.
#### Date-time component options
- `weekday`
- : The representation of the weekday. Possible values are:
- `"long"`
- : E.g., `Thursday`
- `"short"`
- : E.g., `Thu`
- `"narrow"`
- : E.g., `T`. Two weekdays may have the same narrow style for some locales (e.g. `Tuesday`'s narrow style is also `T`).
- `era`
- : The representation of the era. Possible values are:
- `"long"`
- : E.g., `Anno Domini`
- `"short"`
- : E.g., `AD`
- `"narrow"`
- : E.g., `A`
- `year`
- : The representation of the year. Possible values are `"numeric"` and `"2-digit"`.
- `month`
- : The representation of the month. Possible values are:
- `"numeric"`
- : E.g., `3`
- `"2-digit"`
- : E.g., `03`
- `"long"`
- : E.g., `March`
- `"short"`
- : E.g., `Mar`
- `"narrow"`
- : E.g., `M`). Two months may have the same narrow style for some locales (e.g. `May`'s narrow style is also `M`).
- `day`
- : The representation of the day. Possible values are `"numeric"` and `"2-digit"`.
- `dayPeriod`
- : The formatting style used for day periods like "in the morning", "am", "noon", "n" etc. Possible values are
`"narrow"`, `"short"`, and `"long"`.
> **Note:** This option only has an effect if a 12-hour clock (`hourCycle: "h12"` or `hourCycle: "h11"`) is used. Many locales use the same string irrespective of the width specified.
- `hour`
- : The representation of the hour. Possible values are `"numeric"` and `"2-digit"`.
- `minute`
- : The representation of the minute. Possible values are `"numeric"` and `"2-digit"`.
- `second`
- : The representation of the second. Possible values are `"numeric"` and `"2-digit"`.
- `fractionalSecondDigits`
- : The number of digits used to represent fractions of a second (any additional digits are truncated). Possible values are from `1` to `3`.
- `timeZoneName`
- : The localized representation of the time zone name. Possible values are:
- `"long"`
- : Long localized form (e.g., `Pacific Standard Time`, `Nordamerikanische Westküsten-Normalzeit`)
- `"short"`
- : Short localized form (e.g.: `PST`, `GMT-8`)
- `"shortOffset"`
- : Short localized GMT format (e.g., `GMT-8`)
- `"longOffset"`
- : Long localized GMT format (e.g., `GMT-08:00`)
- `"shortGeneric"`
- : Short generic non-location format (e.g.: `PT`, `Los Angeles Zeit`).
- `"longGeneric"`
- : Long generic non-location format (e.g.: `Pacific Time`, `Nordamerikanische Westküstenzeit`)
> **Note:** Timezone display may fall back to another format if a required string is unavailable. For example, the non-location formats should display the timezone without a specific country/city location like "Pacific Time", but may fall back to a timezone like "Los Angeles Time".
The default value for each date-time component option is {{jsxref("undefined")}}, but if all component properties are {{jsxref("undefined")}}, then `year`, `month`, and `day` default to `"numeric"`. If any of the date-time component options is specified, then `dateStyle` and `timeStyle` must be `undefined`.
- `formatMatcher`
- : The format matching algorithm to use. Possible values are `"basic"` and `"best fit"`; the default is `"best fit"`. Implementations are required to support displaying at least the following subsets of date-time components:
- `weekday`, `year`, `month`, `day`, `hour`, `minute`, `second`
- `weekday`, `year`, `month`, `day`
- `year`, `month`, `day`
- `year`, `month`
- `month`, `day`
- `hour`, `minute`, `second`
- `hour`, `minute`
Implementations may support other subsets, and requests will be negotiated against all available subset-representation combinations to find the best match. The algorithm for `"best fit"` is implementation-defined, and `"basic"` is [defined by the spec](https://tc39.es/ecma402/#sec-basicformatmatcher). This option is only used when both `dateStyle` and `timeStyle` are `undefined` (so that each date-time component's format is individually customizable).
#### Style shortcuts
- `dateStyle`
- : The date formatting style to use when calling `format()`. Possible values are `"full"`, `"long"`, `"medium"`, and `"short"`.
- `timeStyle`
- : The time formatting style to use when calling `format()`. Possible values are `"full"`, `"long"`, `"medium"`, and `"short"`.
> **Note:** `dateStyle` and `timeStyle` can be used with each other, but not with other date-time component options (e.g. `weekday`, `hour`, `month`, etc.).
### Return value
A new `Intl.DateTimeFormat` object.
> **Note:** The text below describes behavior that is marked by the specification as "optional". It may not work in all environments. Check the [browser compatibility table](#browser_compatibility).
Normally, `Intl.DateTimeFormat()` can be called with or without [`new`](/en-US/docs/Web/JavaScript/Reference/Operators/new), and a new `Intl.DateTimeFormat` instance is returned in both cases. However, if the [`this`](/en-US/docs/Web/JavaScript/Reference/Operators/this) value is an object that is [`instanceof`](/en-US/docs/Web/JavaScript/Reference/Operators/instanceof) `Intl.DateTimeFormat` (doesn't necessarily mean it's created via `new Intl.DateTimeFormat`; just that it has `Intl.DateTimeFormat.prototype` in its prototype chain), then the value of `this` is returned instead, with the newly created `Intl.DateTimeFormat` object hidden in a `[Symbol(IntlLegacyConstructedSymbol)]` property (a unique symbol that's reused between instances).
```js
const formatter = Intl.DateTimeFormat.call(
{ __proto__: Intl.DateTimeFormat.prototype },
"en-US",
{ dateStyle: "full" },
);
console.log(Object.getOwnPropertyDescriptors(formatter));
// {
// [Symbol(IntlLegacyConstructedSymbol)]: {
// value: DateTimeFormat [Intl.DateTimeFormat] {},
// writable: false,
// enumerable: false,
// configurable: false
// }
// }
```
Note that there's only one actual `Intl.DateTimeFormat` instance here: the one hidden in `[Symbol(IntlLegacyConstructedSymbol)]`. Calling the [`format()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/format) and [`resolvedOptions()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/resolvedOptions) methods on `formatter` would correctly use the options stored in that instance, but calling all other methods (e.g. [`formatRange()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/formatRange)) would fail: "TypeError: formatRange method called on incompatible Object", because those methods don't consult the hidden instance's options.
This behavior, called `ChainDateTimeFormat`, does not happen when `Intl.DateTimeFormat()` is called without `new` but with `this` set to anything else that's not an `instanceof Intl.DateTimeFormat`. If you call it directly as `Intl.DateTimeFormat()`, the `this` value is [`Intl`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl), and a new `Intl.DateTimeFormat` instance is created normally.
### Exceptions
- {{jsxref("RangeError")}}
- : Thrown if `locales` or `options` contain invalid values.
## Examples
### Using DateTimeFormat
In basic use without specifying a locale, `DateTimeFormat` uses the default
locale and default options.
```js
const date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));
// toLocaleString without arguments depends on the implementation,
// the default locale, and the default time zone
console.log(new Intl.DateTimeFormat().format(date));
// "12/19/2012" if run with en-US locale (language) and time zone America/Los_Angeles (UTC-0800)
```
### Using timeStyle and dateStyle
```js
const shortTime = new Intl.DateTimeFormat("en", {
timeStyle: "short",
});
console.log(shortTime.format(Date.now())); // "1:31 PM"
const shortDate = new Intl.DateTimeFormat("en", {
dateStyle: "short",
});
console.log(shortDate.format(Date.now())); // "07/07/20"
const mediumTime = new Intl.DateTimeFormat("en", {
timeStyle: "medium",
dateStyle: "short",
});
console.log(mediumTime.format(Date.now())); // "07/07/20, 1:31:55 PM"
```
### Using dayPeriod
Use the `dayPeriod` option to output a string for the times of day ("in the morning", "at night", "noon", etc.). Note, that this only works when formatting for a 12 hour clock (`hourCycle: 'h12'` or `hourCycle: 'h11'`) and that for many locales the strings are the same irrespective of the value passed for the `dayPeriod`.
```js
const date = Date.UTC(2012, 11, 17, 4, 0, 42);
console.log(
new Intl.DateTimeFormat("en-GB", {
hour: "numeric",
hourCycle: "h12",
dayPeriod: "short",
timeZone: "UTC",
}).format(date),
);
// 4 at night" (same formatting in en-GB for all dayPeriod values)
console.log(
new Intl.DateTimeFormat("fr", {
hour: "numeric",
hourCycle: "h12",
dayPeriod: "narrow",
timeZone: "UTC",
}).format(date),
);
// "4 mat." (same output in French for both narrow/short dayPeriod)
console.log(
new Intl.DateTimeFormat("fr", {
hour: "numeric",
hourCycle: "h12",
dayPeriod: "long",
timeZone: "UTC",
}).format(date),
);
// "4 du matin"
```
### Using timeZoneName
Use the `timeZoneName` option to output a string for the timezone ("GMT", "Pacific Time", etc.).
```js
const date = Date.UTC(2021, 11, 17, 3, 0, 42);
const timezoneNames = [
"short",
"long",
"shortOffset",
"longOffset",
"shortGeneric",
"longGeneric",
];
for (const zoneName of timezoneNames) {
// Do something with currentValue
const formatter = new Intl.DateTimeFormat("en-US", {
timeZone: "America/Los_Angeles",
timeZoneName: zoneName,
});
console.log(`${zoneName}: ${formatter.format(date)}`);
}
// Logs:
// short: 12/16/2021, PST
// long: 12/16/2021, Pacific Standard Time
// shortOffset: 12/16/2021, GMT-8
// longOffset: 12/16/2021, GMT-08:00
// shortGeneric: 12/16/2021, PT
// longGeneric: 12/16/2021, Pacific Time
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Intl.DateTimeFormat")}}
- {{jsxref("Intl.supportedValuesOf()")}}
- {{jsxref("Intl")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/datetimeformat | data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/datetimeformat/supportedlocalesof/index.md | ---
title: Intl.DateTimeFormat.supportedLocalesOf()
slug: Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/supportedLocalesOf
page-type: javascript-static-method
browser-compat: javascript.builtins.Intl.DateTimeFormat.supportedLocalesOf
---
{{JSRef}}
The **`Intl.DateTimeFormat.supportedLocalesOf()`** static method returns an array containing those of the provided locales that are supported in date and time formatting without having to fall back to the runtime's default locale.
{{EmbedInteractiveExample("pages/js/intl-datetimeformat-supportedlocalesof.html", "shorter")}}
## Syntax
```js-nolint
Intl.DateTimeFormat.supportedLocalesOf(locales)
Intl.DateTimeFormat.supportedLocalesOf(locales, options)
```
### Parameters
- `locales`
- : A string with a BCP 47 language tag, or an array of such strings. For the general form and interpretation of the `locales` argument, see [the parameter description on the `Intl` main page](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#locales_argument).
- `options` {{optional_inline}}
- : An object that may have the following property:
- `localeMatcher`
- : The locale matching algorithm to use. Possible values are `"lookup"` and `"best fit"`; the default is `"best fit"`. For information about this option, see the {{jsxref("Intl", "Intl", "#locale_identification_and_negotiation", 1)}} page.
### Return value
An array of strings representing a subset of the given locale tags that are supported in date and time formatting without having to fall back to the runtime's default locale.
## Examples
### Using supportedLocalesOf()
Assuming a runtime that supports Indonesian and German but not Balinese in date and time formatting, `supportedLocalesOf` returns the Indonesian and German language tags unchanged, even though `pinyin` collation is neither relevant to date and time formatting nor used with Indonesian, and a specialized German for Indonesia is unlikely to be supported. Note the specification of the `"lookup"` algorithm here — a `"best fit"` matcher might decide that Indonesian is an adequate match for Balinese since most Balinese speakers also understand Indonesian, and therefore return the Balinese language tag as well.
```js
const locales = ["ban", "id-u-co-pinyin", "de-ID"];
const options = { localeMatcher: "lookup" };
console.log(Intl.DateTimeFormat.supportedLocalesOf(locales, options));
// ["id-u-co-pinyin", "de-ID"]
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Intl.DateTimeFormat")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl | data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/numberformat/index.md | ---
title: Intl.NumberFormat
slug: Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat
page-type: javascript-class
browser-compat: javascript.builtins.Intl.NumberFormat
---
{{JSRef}}
The **`Intl.NumberFormat`** object enables language-sensitive number formatting.
{{EmbedInteractiveExample("pages/js/intl-numberformat.html")}}
## Constructor
- {{jsxref("Intl/NumberFormat/NumberFormat", "Intl.NumberFormat()")}}
- : Creates a new `NumberFormat` object.
## Static methods
- {{jsxref("Intl/NumberFormat/supportedLocalesOf", "Intl.NumberFormat.supportedLocalesOf()")}}
- : Returns an array containing those of the provided locales that are supported without having to fall back to the runtime's default locale.
## Instance properties
These properties are defined on `Intl.NumberFormat.prototype` and shared by all `Intl.NumberFormat` instances.
- {{jsxref("Object/constructor", "Intl.NumberFormat.prototype.constructor")}}
- : The constructor function that created the instance object. For `Intl.NumberFormat` instances, the initial value is the {{jsxref("Intl/NumberFormat/NumberFormat", "Intl.NumberFormat")}} constructor.
- `Intl.NumberFormat.prototype[@@toStringTag]`
- : The initial value of the [`@@toStringTag`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/toStringTag) property is the string `"Intl.NumberFormat"`. This property is used in {{jsxref("Object.prototype.toString()")}}.
## Instance methods
- {{jsxref("Intl/NumberFormat/format", "Intl.NumberFormat.prototype.format()")}}
- : Getter function that formats a number according to the locale and formatting options of this {{jsxref("Intl.NumberFormat")}} object.
- {{jsxref("Intl/NumberFormat/formatRange", "Intl.NumberFormat.prototype.formatRange()")}}
- : Getter function that formats a range of numbers according to the locale and formatting options of the {{jsxref("Intl.NumberFormat")}} object from which the method is called.
- {{jsxref("Intl/NumberFormat/formatRangeToParts", "Intl.NumberFormat.prototype.formatRangeToParts()")}}
- : Returns an {{jsxref("Array")}} of objects representing the range of number strings in parts that can be used for custom locale-aware formatting.
- {{jsxref("Intl/NumberFormat/formatToParts", "Intl.NumberFormat.prototype.formatToParts()")}}
- : Returns an {{jsxref("Array")}} of objects representing the number string in parts that can be used for custom locale-aware formatting.
- {{jsxref("Intl/NumberFormat/resolvedOptions", "Intl.NumberFormat.prototype.resolvedOptions()")}}
- : Returns a new object with properties reflecting the locale and collation options computed during initialization of the object.
## Examples
### Basic usage
In basic use without specifying a locale, a formatted string in the default locale and with default options is returned.
```js
const number = 3500;
console.log(new Intl.NumberFormat().format(number));
// '3,500' if in US English locale
```
### Using locales
This example shows some of the variations in localized number formats. In order to get the format of the language used in the user interface of your application, make sure to specify that language (and possibly some fallback languages) using the `locales` argument:
```js
const number = 123456.789;
// German uses comma as decimal separator and period for thousands
console.log(new Intl.NumberFormat("de-DE").format(number));
// 123.456,789
// Arabic in most Arabic speaking countries uses real Arabic digits
console.log(new Intl.NumberFormat("ar-EG").format(number));
// ١٢٣٤٥٦٫٧٨٩
// India uses thousands/lakh/crore separators
console.log(new Intl.NumberFormat("en-IN").format(number));
// 1,23,456.789
// the nu extension key requests a numbering system, e.g. Chinese decimal
console.log(new Intl.NumberFormat("zh-Hans-CN-u-nu-hanidec").format(number));
// 一二三,四五六.七八九
// when requesting a language that may not be supported, such as
// Balinese, include a fallback language, in this case Indonesian
console.log(new Intl.NumberFormat(["ban", "id"]).format(number));
// 123.456,789
```
### Using options
The results can be customized using the [`options`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#options) argument:
```js
const number = 123456.789;
// request a currency format
console.log(
new Intl.NumberFormat("de-DE", { style: "currency", currency: "EUR" }).format(
number,
),
);
// 123.456,79 €
// the Japanese yen doesn't use a minor unit
console.log(
new Intl.NumberFormat("ja-JP", { style: "currency", currency: "JPY" }).format(
number,
),
);
// ¥123,457
// limit to three significant digits
console.log(
new Intl.NumberFormat("en-IN", { maximumSignificantDigits: 3 }).format(
number,
),
);
// 1,23,000
// Formatting with units
console.log(
new Intl.NumberFormat("pt-PT", {
style: "unit",
unit: "kilometer-per-hour",
}).format(50),
);
// 50 km/h
console.log(
(16).toLocaleString("en-GB", {
style: "unit",
unit: "liter",
unitDisplay: "long",
}),
);
// 16 litres
```
For an exhaustive list of options, see the [`Intl.NumberFormat()` constructor](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#options) page.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `Intl.NumberFormat` in FormatJS](https://formatjs.io/docs/polyfills/intl-numberformat/)
- {{jsxref("Intl")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/numberformat | data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/numberformat/formatrange/index.md | ---
title: Intl.NumberFormat.prototype.formatRange()
slug: Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/formatRange
page-type: javascript-instance-method
browser-compat: javascript.builtins.Intl.NumberFormat.formatRange
---
{{JSRef}}
The **`formatRange()`** method of {{jsxref("Intl.NumberFormat")}} instances formats a range of numbers according to the locale and formatting options of this `Intl.NumberFormat` object.
## Syntax
```js-nolint
formatRange(startRange, endRange)
```
### Parameters
- `startRange`
- : A {{jsxref("Number")}} or {{jsxref("BigInt")}}.
- `endRange`
- : A {{jsxref("Number")}} or {{jsxref("BigInt")}}.
### Return value
A string representing the given range of numbers formatted according to the locale and formatting options of this {{jsxref("Intl.NumberFormat")}} object.
### Exceptions
- {{jsxref("RangeError")}}
- : Thrown if `startRange` is less than `endRange`, or either value is `NaN`.
- {{jsxref("TypeError")}}
- : Thrown if either `startRange` or `endRange` is undefined.
## Description
The `formatRange` getter function formats a range of numbers into a string according to the locale and formatting options of this {{jsxref("Intl.NumberFormat")}} object from which it is called.
## Examples
### Using formatRange
Use the `formatRange` getter function for formatting a range of currency values:
```js
const nf = new Intl.NumberFormat("en-US", {
style: "currency",
currency: "USD",
maximumFractionDigits: 0,
});
console.log(nf.formatRange(3, 5)); // "$3 – $5"
// Note: the "approximately equals" symbol is added if
// startRange and endRange round to the same values.
console.log(nf.formatRange(2.9, 3.1)); // "~$3"
```
```js
const nf = new Intl.NumberFormat("es-ES", {
style: "currency",
currency: "EUR",
maximumFractionDigits: 0,
});
console.log(nf.formatRange(3, 5)); // "3-5 €"
console.log(nf.formatRange(2.9, 3.1)); // "~3 €"
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Intl.NumberFormat")}}
- {{jsxref("Number.prototype.toLocaleString()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/numberformat | data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/numberformat/format/index.md | ---
title: Intl.NumberFormat.prototype.format()
slug: Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/format
page-type: javascript-instance-method
browser-compat: javascript.builtins.Intl.NumberFormat.format
---
{{JSRef}}
The **`format()`** method of {{jsxref("Intl.NumberFormat")}} instances formats a number according to the [locale and formatting options](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#parameters) of this `Intl.NumberFormat` object.
{{EmbedInteractiveExample("pages/js/intl-numberformat-prototype-format.html", "taller")}}
## Syntax
```js-nolint
format(number)
```
### Parameters
- `number`
- : A {{jsxref("Number")}}, {{jsxref("BigInt")}}, or string, to format. Strings are parsed in the same way as in [number conversion](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number#number_coercion), except that `format()` will use the exact value that the string represents, avoiding loss of precision during implicitly conversion to a number.
> **Note:** Older versions of the specification parsed strings as a {{jsxref("Number")}}.
> Check the compatibility table for your browser.
### Return value
A string representing the given `number` formatted according to the locale and formatting options of this {{jsxref("Intl.NumberFormat")}} object.
## Description
{{jsxref("Number")}} values in JavaScript suffer from loss of precision if they are too big or too small, making the text representation inaccurate.
If you are performing calculations with integers larger than {{jsxref("Number.MAX_SAFE_INTEGER")}} you should use a {{jsxref("BigInt")}} instead, which will format correctly:
```js
new Intl.NumberFormat("en-US").format(1234567891234567891); // 1,234,567,891,234,568,000
new Intl.NumberFormat("en-US").format(1234567891234567891n); // 1,234,567,891,234,567,891
```
You can also pass through very large strings to be formatted as an arbitrary-precision decimal string (if you're performing calculations on the data you will still need to work with `BigInt`):
```js
new Intl.NumberFormat("en-US").format("1234567891234567891"); // 1,234,567,891,234,567,891
```
## Examples
### Using format
Use the `format` getter function for formatting a single currency value.
The code below shows how to format the roubles currency for a Russian locale:
```js
const options = { style: "currency", currency: "RUB" };
const numberFormat = new Intl.NumberFormat("ru-RU", options);
console.log(numberFormat.format(654321.987));
// "654 321,99 ₽"
```
### Using format with map
Use the `format` getter function for formatting all numbers in an array.
Note that the function is bound to the {{jsxref("Intl.NumberFormat")}} from which it was obtained, so it can be passed directly to {{jsxref("Array.prototype.map")}}.
This is considered a historical artefact, as part of a convention which is no longer followed for new features, but is preserved to maintain compatibility with existing programs.
```js
const a = [123456.789, 987654.321, 456789.123];
const numberFormat = new Intl.NumberFormat("es-ES");
const formatted = a.map((n) => numberFormat.format(n));
console.log(formatted.join("; "));
// "123.456,789; 987.654,321; 456.789,123"
```
### Using format with a string
Using a string we can specify very numbers that are larger than {{jsxref("Number.MAX_SAFE_INTEGER")}} without losing precision.
```js
const numberFormat = new Intl.NumberFormat("en-US");
// Here the value is converted to a Number
console.log(numberFormat.format(987654321987654321));
// 987,654,321,987,654,300
// Here we use a string and don't lose precision
console.log(numberFormat.format("987654321987654321"));
// 987,654,321,987,654,321
```
We can also use the general "E" exponent syntax for decimal strings: `#.#E#`.
The code below creates a {{jsxref("BigInt")}}, coerces it to a string with the suffix `E-6`, and then formats it.
```js
const numberFormat = new Intl.NumberFormat("en-US");
const bigNum = 1000000000000000110000n;
console.log(numberFormat.format(bigNum));
// "1,000,000,000,000,000,110,000"
// Format as a string using the `E` syntax:
console.log(numberFormat.format(`${bigNum}E-6`));
// "1,000,000,000,000,000.11"
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Intl.NumberFormat")}}
- {{jsxref("Number.prototype.toLocaleString()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/numberformat | data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/numberformat/resolvedoptions/index.md | ---
title: Intl.NumberFormat.prototype.resolvedOptions()
slug: Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/resolvedOptions
page-type: javascript-instance-method
browser-compat: javascript.builtins.Intl.NumberFormat.resolvedOptions
---
{{JSRef}}
The **`resolvedOptions()`** method of {{jsxref("Intl.NumberFormat")}} instances returns a new object with properties reflecting the [locale and number formatting options](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#parameters) computed during initialization of this `Intl.NumberFormat` object.
{{EmbedInteractiveExample("pages/js/intl-numberformat-prototype-resolvedoptions.html")}}
## Syntax
```js-nolint
resolvedOptions()
```
### Parameters
None.
### Return value
A new object with properties reflecting the [locale and number formatting options](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#parameters) computed during the construction of the given {{jsxref("Intl.NumberFormat")}} object.
The resulting object has the following properties:
- `compactDisplay`
- : Whether to use short or long form when using compact notation.
This is the value provided in the [`options.compactDisplay`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#compactdisplay) argument of the constructor, or the default value: `"short"`.
The value is only present if `notation` is set to "compact", and otherwise is `undefined`.
- `currency`
- : The currency to use in currency formatting.
The value is defined if `style` is `"currency"`, and is otherwise `undefined`.
This is the value provided in the [`options.currency`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#currency) argument of the constructor.
- `currencyDisplay`
- : The display format for the currency, such as a symbol, or currency code.
The value is defined if `style` is `"currency"`, and otherwise is `undefined`.
This is the value provided in the [`options.currencyDisplay`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#currencydisplay) argument of the constructor, or the default value: `"symbol"`.
- `currencySign`
- : The method used to specify the sign of the currency value: `standard` or `accounting`.
The value is present if `style` is `"currency"`, and otherwise is `undefined`.
This is the value provided in the [`options.currencySign`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#currencysign) argument of the constructor, or the default value: `"standard"`.
- `locale`
- : The BCP 47 language tag for the locale that was actually used.
The key-value pairs that were requested in the constructor [`locale`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#local) and are supported for this locale are included.
- `notation`
- : The formatting that should be applied to the number, such as `standard` or `engineering`.
This is the value provided in the [`options.notation`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#notation) argument of the constructor, or the default value: `"standard"`.
- `numberingSystem`
- : The numbering system.
This is the value provided in the [`options.numberingSystem`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#numberingsystem) argument of the constructor, if present, or the value set using the Unicode extension key [`nu`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#nu), or filled in as a default.
- `roundingMode`
- : The rounding mode.
This is the value provided for the [`options.roundingMode`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#roundingmode) argument in the constructor, or the default value: `halfExpand`.
- `roundingPriority`
- : The priority for resolving rounding conflicts if both "FractionDigits" and "SignificantDigits" are specified.
This is the value provided for the [`options.roundingPriority`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#roundingpriority) argument in the constructor, or the default value: `auto`.
- `roundingIncrement`
- : The rounding-increment precision (the increment used when rounding numbers).
This is the value specified in the [`options.roundingIncrement`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#roundingincrement) argument in the constructor.
- `signDisplay`
- : Whether or not to display the positive/negative sign.
This is the value specified in the [`options.signDisplay`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#signdisplay) argument in the constructor, or the default value: `"auto"`.
- `unit`
- : The unit to use in unit formatting.
The value is only present if `style` is `"unit"`, and is otherwise `undefined`.
This is the value specified in the [`options.unit`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#unit) argument in the constructor.
- `unitDisplay`
- : The display format to use for units in unit formatting, such as "long", "short" or "narrow".
The value is only present if `style` is `"unit"`, and is otherwise `undefined`.
This is the value specified in the [`options.unitDisplay`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#unitdisplay) argument in the constructor, or the default value: `short`.
- `useGrouping`
- : Whether or not to use grouping separators to indicate "thousands", "millions" and son on.
This is the value specified in the [`options.useGrouping`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#usegrouping) argument in the constructor, or the default value: `"auto"`.
- `trailingZeroDisplay`
- : The strategy for displaying trailing zeros on whole numbers.
This is the value specified in the [`options.trailingZeroDisplay`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat#trailingzerodisplay) argument in the constructor, or the default value: `"auto"`.
Only one of the following two groups of properties is included:
- `minimumIntegerDigits`, `minimumFractionDigits`, `maximumFractionDigits`
- : The values provided for these properties in the `options` argument or filled in as defaults.
These properties are present only if neither `minimumSignificantDigits` nor `maximumSignificantDigits` was provided in the `options` argument.
- `minimumSignificantDigits`, `maximumSignificantDigits`
- : The values provided for these properties in the `options` argument or filled in as defaults.
These properties are present only if at least one of them was provided in the `options` argument.
## Examples
### Using the `resolvedOptions` method
```js
// Create a NumberFormat
const de = new Intl.NumberFormat("de-DE", {
style: "currency",
currency: "USD",
maximumFractionDigits: 2,
roundingIncrement: 5,
roundingMode: "halfCeil",
});
// Resolve the options
const usedOptions = de.resolvedOptions();
console.log(usedOptions.locale); // "de-DE"
console.log(usedOptions.numberingSystem); // "latn"
console.log(usedOptions.compactDisplay); // undefined ("notation" not set to "compact")
console.log(usedOptions.currency); // "USD"
console.log(usedOptions.currencyDisplay); // "symbol"
console.log(usedOptions.currencySign); // "standard"
console.log(usedOptions.minimumIntegerDigits); // 1
console.log(usedOptions.minimumFractionDigits); // 2
console.log(usedOptions.maximumFractionDigits); // 2
console.log(usedOptions.minimumSignificantDigits); // undefined (maximumFractionDigits is set)
console.log(usedOptions.maximumSignificantDigits); // undefined (maximumFractionDigits is set)
console.log(usedOptions.notation); // "standard"
console.log(usedOptions.roundingIncrement); // 5
console.log(usedOptions.roundingMode); // halfCeil
console.log(usedOptions.roundingPriority); // auto
console.log(usedOptions.signDisplay); // "auto"
console.log(usedOptions.style); // "currency"
console.log(usedOptions.trailingZeroDisplay); // auto
console.log(usedOptions.useGrouping); // auto
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Intl.NumberFormat")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/numberformat | data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/numberformat/formatrangetoparts/index.md | ---
title: Intl.NumberFormat.prototype.formatRangeToParts()
slug: Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/formatRangeToParts
page-type: javascript-instance-method
browser-compat: javascript.builtins.Intl.NumberFormat.formatRangeToParts
---
{{JSRef}}
The **`formatRangeToParts()`** method of {{jsxref("Intl.NumberFormat")}} instances returns an {{jsxref("Array")}} of objects containing the locale-specific tokens from which it is possible to build custom strings while preserving the locale-specific parts. This makes it possible to provide locale-aware custom formatting ranges of number strings.
## Syntax
```js-nolint
formatRangeToParts(startRange, endRange)
```
### Parameters
- `startRange`
- : A {{jsxref("Number")}} or {{jsxref("BigInt")}}.
- `endRange`
- : A {{jsxref("Number")}} or {{jsxref("BigInt")}}.
### Return value
An {{jsxref("Array")}} of objects containing the formatted range of numbers in parts.
The structure of the returned looks like this:
```js
[
{ type: "integer", value: "3", source: "startRange" },
{ type: "literal", value: "-", source: "shared" },
{ type: "integer", value: "5", source: "endRange" },
{ type: "literal", value: " ", source: "shared" },
{ type: "currency", value: "€", source: "shared" },
];
```
Possible values for the `type` property include:
- `currency`
- : The currency string, such as the symbols "$" and "€" or the name "Dollar", "Euro", depending on how `currencyDisplay` is specified.
- `decimal`
- : The decimal separator string (".").
- `fraction`
- : The fraction number.
- `group`
- : The group separator string (",").
- `infinity`
- : The {{jsxref("Infinity")}} string ("∞").
- `integer`
- : The integer number.
- `literal`
- : Any literal strings or whitespace in the formatted number.
- `minusSign`
- : The minus sign string ("-").
- `nan`
- : The {{jsxref("NaN")}} string ("NaN").
- `plusSign`
- : The plus sign string ("+").
- `percentSign`
- : The percent sign string ("%").
- `unit`
- : The unit string, such as the "l" or "litres", depending on how `unitDisplay` is specified.
Possible values for the `source` property include:
- `startRange`
- : The object is the start part of the range.
- `endRange`
- : The object is the end part of the range.
- `shared`
- : The object is a "shared" part of the range, such as a separator or currency.
### Exceptions
- {{jsxref("RangeError")}}
- : Thrown if `startRange` is less than `endRange`, or either value is `NaN`.
- {{jsxref("TypeError")}}
- : Thrown if either `startRange` or `endRange` is undefined.
## Examples
### Comparing formatRange and formatRangeToParts
`NumberFormat` outputs localized, opaque strings that cannot be manipulated directly:
```js
const startRange = 3500;
const endRange = 9500;
const formatter = new Intl.NumberFormat("de-DE", {
style: "currency",
currency: "EUR",
});
console.log(formatter.formatRange(startRange, endRange));
// "3.500,00–9.500,00 €"
```
However, for many user interfaces there is a need to customize the formatting of this string.
The `formatRangeToParts` method enables locale-aware formatting of strings produced by `NumberFormat` formatters by providing you the string in parts:
```js
console.log(formatter.formatRangeToParts(startRange, endRange));
// return value:
[
{ type: "integer", value: "3", source: "startRange" },
{ type: "group", value: ".", source: "startRange" },
{ type: "integer", value: "500", source: "startRange" },
{ type: "decimal", value: ",", source: "startRange" },
{ type: "fraction", value: "00", source: "startRange" },
{ type: "literal", value: "–", source: "shared" },
{ type: "integer", value: "9", source: "endRange" },
{ type: "group", value: ".", source: "endRange" },
{ type: "integer", value: "500", source: "endRange" },
{ type: "decimal", value: ",", source: "endRange" },
{ type: "fraction", value: "00", source: "endRange" },
{ type: "literal", value: " ", source: "shared" },
{ type: "currency", value: "€", source: "shared" },
];
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Intl.NumberFormat")}}
- {{jsxref("Intl/NumberFormat/format", "Intl.NumberFormat.prototype.format()")}}
- {{jsxref("Intl/DateTimeFormat/formatRangeToParts", "Intl.DateTimeFormat.prototype.formatRangeToParts()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/numberformat | data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/numberformat/formattoparts/index.md | ---
title: Intl.NumberFormat.prototype.formatToParts()
slug: Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/formatToParts
page-type: javascript-instance-method
browser-compat: javascript.builtins.Intl.NumberFormat.formatToParts
---
{{JSRef}}
The **`formatToParts()`** method of {{jsxref("Intl.NumberFormat")}} instances allows locale-aware formatting of strings produced by this `Intl.NumberFormat` object.
{{EmbedInteractiveExample("pages/js/intl-numberformat-prototype-formattoparts.html")}}
## Syntax
```js-nolint
formatToParts()
formatToParts(number)
```
### Parameters
- `number` {{optional_inline}}
- : A {{jsxref("Number")}} or {{jsxref("BigInt")}} to format.
### Return value
An {{jsxref("Array")}} of objects containing the formatted number in parts.
## Description
The `formatToParts()` method is useful for custom formatting of number
strings. It returns an {{jsxref("Array")}} of objects containing the locale-specific
tokens from which it possible to build custom strings while preserving the
locale-specific parts. The structure the `formatToParts()` method returns,
looks like this:
```js
[
{ type: "integer", value: "3" },
{ type: "group", value: "." },
{ type: "integer", value: "500" },
];
```
Possible types are the following:
- `compact`
- : The exponent in `"long"` or `"short"` form, depending on how `compactDisplay` (which defaults to `short`) is specified when `notation` is set to `compact`.
- `currency`
- : The currency string, such as the symbols "$" and "€" or the name "Dollar", "Euro", depending on how `currencyDisplay` is specified.
- `decimal`
- : The decimal separator string (".").
- `exponentInteger`
- : The exponent integer value, when `notation` is set to `scientific` or `engineering`.
- `exponentMinusSign`
- : The exponent minus sign string ("-").
- `exponentSeparator`
- : The exponent separator, when `notation` is set to `scientific` or `engineering`.
- `fraction`
- : The fraction number.
- `group`
- : The group separator string (",").
- `infinity`
- : The {{jsxref("Infinity")}} string ("∞").
- `integer`
- : The integer number.
- `literal`
- : Any literal strings or whitespace in the formatted number.
- `minusSign`
- : The minus sign string ("-").
- `nan`
- : The {{jsxref("NaN")}} string ("NaN").
- `plusSign`
- : The plus sign string ("+").
- `percentSign`
- : The percent sign string ("%").
- `unit`
- : The unit string, such as the "l" or "litres", depending on how `unitDisplay` is specified.
- `unknown`
- : The string for `unknown` type results.
## Examples
### Comparing format and formatToParts
`NumberFormat` outputs localized, opaque strings that cannot be manipulated
directly:
```js
const number = 3500;
const formatter = new Intl.NumberFormat("de-DE", {
style: "currency",
currency: "EUR",
});
formatter.format(number);
// "3.500,00 €"
```
However, in many User Interfaces there is a desire to customize the formatting of this
string. The `formatToParts` method enables locale-aware formatting of
strings produced by `NumberFormat` formatters by providing you the string
in parts:
```js
formatter.formatToParts(number);
// return value:
[
{ type: "integer", value: "3" },
{ type: "group", value: "." },
{ type: "integer", value: "500" },
{ type: "decimal", value: "," },
{ type: "fraction", value: "00" },
{ type: "literal", value: " " },
{ type: "currency", value: "€" },
];
```
Now the information is available separately and it can be formatted and concatenated
again in a customized way. For example by using {{jsxref("Array.prototype.map()")}},
[arrow functions](/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions),
a [switch statement](/en-US/docs/Web/JavaScript/Reference/Statements/switch),
[template literals](/en-US/docs/Web/JavaScript/Reference/Template_literals), and {{jsxref("Array.prototype.reduce()")}}.
```js
const numberString = formatter
.formatToParts(number)
.map(({ type, value }) => {
switch (type) {
case "currency":
return `<strong>${value}</strong>`;
default:
return value;
}
})
.reduce((string, part) => string + part);
```
This will make the currency bold, when using the `formatToParts()` method.
```js
console.log(numberString);
// "3.500,00 <strong>€</strong>"
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Intl.NumberFormat")}}
- {{jsxref("Intl/NumberFormat/format", "Intl.NumberFormat.prototype.format()")}}
- {{jsxref("Intl/DateTimeFormat/formatToParts", "Intl.DateTimeFormat.prototype.formatToParts()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/numberformat | data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/numberformat/numberformat/index.md | ---
title: Intl.NumberFormat() constructor
slug: Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/NumberFormat
page-type: javascript-constructor
browser-compat: javascript.builtins.Intl.NumberFormat.NumberFormat
---
{{JSRef}}
The **`Intl.NumberFormat()`** constructor creates {{jsxref("Intl.NumberFormat")}} objects.
{{EmbedInteractiveExample("pages/js/intl-numberformat.html", "taller")}}
## Syntax
```js-nolint
new Intl.NumberFormat()
new Intl.NumberFormat(locales)
new Intl.NumberFormat(locales, options)
Intl.NumberFormat()
Intl.NumberFormat(locales)
Intl.NumberFormat(locales, options)
```
> **Note:** `Intl.NumberFormat()` can be called with or without [`new`](/en-US/docs/Web/JavaScript/Reference/Operators/new). Both create a new `Intl.NumberFormat` instance. However, there's a special behavior when it's called without `new` and the `this` value is another `Intl.NumberFormat` instance; see [Return value](#return_value).
### Parameters
- `locales` {{optional_inline}}
- : A string with a BCP 47 language tag or an {{jsxref("Intl.Locale")}} instance, or an array of such locale identifiers. For the general form and interpretation of the `locales` argument, see [the parameter description on the `Intl` main page](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#locales_argument).
The following Unicode extension key is allowed:
- `nu`
- : See [`numberingSystem`](#numberingsystem).
This key can also be set with `options` (as listed below). When both are set, the `options` property takes precedence.
- `options` {{optional_inline}}
- : An object. For ease of reading, the property list is broken into sections based on their purposes, including [locale options](#locale_options), [style options](#style_options), [digit options](#digit_options), and [other options](#other_options).
#### Locale options
- `localeMatcher`
- : The locale matching algorithm to use. Possible values are `"lookup"` and `"best fit"`; the default is `"best fit"`.
For information about this option, see [Locale identification and negotiation](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#locale_identification_and_negotiation).
- `numberingSystem`
- : The numbering system to use for number formatting, such as `"arab"`, `"hans"`, `"mathsans"`, and so on. For a list of supported numbering system types, see [`Intl.Locale.prototype.getNumberingSystems()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Locale/getNumberingSystems#supported_numbering_system_types). This option can also be set through the `nu` Unicode extension key; if both are provided, this `options` property takes precedence.
#### Style options
Depending on the `style` used, some of them may be ignored, and others may be required:
- `style`
- : The formatting style to use.
- `"decimal"` (default)
- : For plain number formatting.
- `"currency"`
- : For currency formatting.
- `"percent"`
- : For percent formatting.
- `"unit"`
- : For unit formatting.
- `currency`
- : The currency to use in currency formatting. Possible values are the ISO 4217 currency codes, such as `"USD"` for the US dollar, `"EUR"` for the euro, or `"CNY"` for the Chinese RMB — see the [Current currency & funds code list](https://en.wikipedia.org/wiki/ISO_4217#List_of_ISO_4217_currency_codes). There is no default value; if the `style` is `"currency"`, the `currency` property must be provided.
- `currencyDisplay`
- : How to display the currency in currency formatting.
- `"code"`
- : Use the ISO currency code.
- `"symbol"` (default)
- : Use a localized currency symbol such as €.
- `"narrowSymbol"`
- : Use a narrow format symbol ("$100" rather than "US$100").
- `"name"`
- : Use a localized currency name such as `"dollar"`.
- `currencySign`
- : In many locales, accounting format means to wrap the number with parentheses instead of appending a minus sign. Possible values are `"standard"` and `"accounting"`; the default is `"standard"`.
- `unit`
- : The unit to use in `unit` formatting, Possible values are core unit identifiers, defined in [UTS #35, Part 2, Section 6](https://unicode.org/reports/tr35/tr35-general.html#Unit_Elements). A [subset](https://tc39.es/ecma402/#table-sanctioned-single-unit-identifiers) of units from the [full list](https://github.com/unicode-org/cldr/blob/main/common/validity/unit.xml) was selected for use in ECMAScript. Pairs of simple units can be concatenated with "-per-" to make a compound unit. There is no default value; if the `style` is `"unit"`, the `unit` property must be provided.
- `unitDisplay`
- : The unit formatting style to use in `unit` formatting. Possible values are:
- `"short"` (default)
- : E.g., `16 l`.
- `"narrow"`
- : E.g., `16l`.
- `"long"`
- : E.g., `16 litres`.
#### Digit options
The following properties are also supported by {{jsxref("Intl.PluralRules")}}.
- `minimumIntegerDigits`
- : The minimum number of integer digits to use. A value with a smaller number of integer digits than this number will be left-padded with zeros (to the specified length) when formatted. Possible values are from `1` to `21`; the default is `1`.
- `minimumFractionDigits`
- : The minimum number of fraction digits to use. Possible values are from `0` to `20`; the default for plain number and percent formatting is `0`; the default for currency formatting is the number of minor unit digits provided by the [ISO 4217 currency code list](https://www.six-group.com/dam/download/financial-information/data-center/iso-currrency/lists/list-one.xml) (2 if the list doesn't provide that information).
- `maximumFractionDigits`
- : The maximum number of fraction digits to use. Possible values are from `0` to `20`; the default for plain number formatting is the larger of `minimumFractionDigits` and `3`; the default for currency formatting is the larger of `minimumFractionDigits` and the number of minor unit digits provided by the [ISO 4217 currency code list](https://www.six-group.com/dam/download/financial-information/data-center/iso-currrency/lists/list-one.xml) (2 if the list doesn't provide that information); the default for percent formatting is the larger of `minimumFractionDigits` and 0.
- `minimumSignificantDigits`
- : The minimum number of significant digits to use. Possible values are from `1` to `21`; the default is `1`.
- `maximumSignificantDigits`
- : The maximum number of significant digits to use. Possible values are from `1` to `21`; the default is `21`.
The above properties fall into two groups: `minimumIntegerDigits`, `minimumFractionDigits`, and `maximumFractionDigits` in one group, `minimumSignificantDigits` and `maximumSignificantDigits` in the other. If properties from both groups are specified, conflicts in the resulting display format are resolved based on the value of the [`roundingPriority`](#roundingpriority) property.
- `roundingPriority`
- : Specify how rounding conflicts will be resolved if both "FractionDigits" ([`minimumFractionDigits`](#minimumfractiondigits)/[`maximumFractionDigits`](#maximumfractiondigits)) and "SignificantDigits" ([`minimumSignificantDigits`](#minimumsignificantdigits)/[`maximumSignificantDigits`](#maximumsignificantdigits)) are specified.
Possible values are:
- `"auto"` (default)
- : The result from the significant digits property is used.
- `"morePrecision"`
- : The result from the property that results in more precision is used.
- `"lessPrecision"`
- : The result from the property that results in less precision is used.
Note that for values other than `auto` the result with more precision is calculated from the [`maximumSignificantDigits`](#minimumsignificantdigits) and [`maximumFractionDigits`](#maximumfractiondigits) (minimum fractional and significant digit settings are ignored).
- `roundingIncrement`
- : Indicates the increment at which rounding should take place relative to the calculated rounding magnitude. Possible values are `1`, `2`, `5`, `10`, `20`, `25`, `50`, `100`, `200`, `250`, `500`, `1000`, `2000`, `2500`, and `5000`. It cannot be mixed with significant-digits rounding or any setting of `roundingPriority` other than `auto`.
- `roundingMode`
- : How decimals should be rounded. Possible values are:
- `"ceil"`
- : Round toward +∞. Positive values round up. Negative values round "more positive".
- `"floor"`
- : Round toward -∞. Positive values round down. Negative values round "more negative".
- `"expand"`
- : round away from 0. The _magnitude_ of the value is always increased by rounding. Positive values round up. Negative values round "more negative".
- `"trunc"`
- : Round toward 0. This _magnitude_ of the value is always reduced by rounding. Positive values round down. Negative values round "less negative".
- `"halfCeil"`
- : ties toward +∞. Values above the half-increment round like `"ceil"` (towards +∞), and below like `"floor"` (towards -∞). On the half-increment, values round like `"ceil"`.
- `"halfFloor"`
- : Ties toward -∞. Values above the half-increment round like `"ceil"` (towards +∞), and below like `"floor"` (towards -∞). On the half-increment, values round like `"floor"`.
- `"halfExpand"` (default)
- : Ties away from 0. Values above the half-increment round like `"expand"` (away from zero), and below like `"trunc"` (towards 0). On the half-increment, values round like `"expand"`.
- `"halfTrunc"`
- : Ties toward 0. Values above the half-increment round like `"expand"` (away from zero), and below like `"trunc"` (towards 0). On the half-increment, values round like `"trunc"`.
- `"halfEven"`
- : Ties towards the nearest even integer. Values above the half-increment round like `"expand"` (away from zero), and below like `"trunc"` (towards 0). On the half-increment values round towards the nearest even digit.
These options reflect the [ICU user guide](https://unicode-org.github.io/icu/userguide/format_parse/numbers/rounding-modes.html), where "expand" and "trunc" map to ICU "UP" and "DOWN", respectively.
The [rounding modes](#rounding_modes) example below demonstrates how each mode works.
- `trailingZeroDisplay`
- : The strategy for displaying trailing zeros on whole numbers. Possible values are:
- `"auto"` (default)
- : Keep trailing zeros according to `minimumFractionDigits` and `minimumSignificantDigits`.
- `"stripIfInteger"`
- : Remove the fraction digits _if_ they are all zero. This is the same as `"auto"` if any of the fraction digits is non-zero.
#### Other options
- `notation`
- : The formatting that should be displayed for the number. Possible values are:
- `"standard"` (default)
- : Plain number formatting.
- `"scientific"`
- : Return the order-of-magnitude for formatted number.
- `"engineering"`
- : Return the exponent of ten when divisible by three.
- `"compact"`
- : String representing exponent; defaults to using the "short" form.
- `compactDisplay`
- : Only used when `notation` is `"compact"`. Possible values are `"short"` and `"long"`; the default is `"short"`.
- `useGrouping`
- : Whether to use grouping separators, such as thousands separators or thousand/lakh/crore separators.
- `"always"`
- : Display grouping separators even if the locale prefers otherwise.
- `"auto"`
- : Display grouping separators based on the locale preference, which may also be dependent on the currency.
- `"min2"`
- : Display grouping separators when there are at least 2 digits in a group.
- `true`
- : Same as `"always"`.
- `false`
- : Display no grouping separators.
The default is `"min2"` if `notation` is `"compact"`, and `"auto"` otherwise. The string values `"true"` and `"false"` are accepted, but are always converted to the default value.
- `signDisplay`
- : When to display the sign for the number. Possible values are:
- `"auto"` (default)
- : Sign display for negative numbers only, including negative zero.
- `"always"`
- : Always display sign.
- `"exceptZero"`
- : Sign display for positive and negative numbers, but not zero.
- `"negative"`
- : Sign display for negative numbers only, excluding negative zero.
- `"never"`
- : Never display sign.
### Return value
A new `Intl.NumberFormat` object.
> **Note:** The text below describes behavior that is marked by the specification as "optional". It may not work in all environments. Check the [browser compatibility table](#browser_compatibility).
Normally, `Intl.NumberFormat()` can be called with or without [`new`](/en-US/docs/Web/JavaScript/Reference/Operators/new), and a new `Intl.NumberFormat` instance is returned in both cases. However, if the [`this`](/en-US/docs/Web/JavaScript/Reference/Operators/this) value is an object that is [`instanceof`](/en-US/docs/Web/JavaScript/Reference/Operators/instanceof) `Intl.NumberFormat` (doesn't necessarily mean it's created via `new Intl.NumberFormat`; just that it has `Intl.NumberFormat.prototype` in its prototype chain), then the value of `this` is returned instead, with the newly created `Intl.NumberFormat` object hidden in a `[Symbol(IntlLegacyConstructedSymbol)]` property (a unique symbol that's reused between instances).
```js
const formatter = Intl.NumberFormat.call(
{ __proto__: Intl.NumberFormat.prototype },
"en-US",
{ notation: "scientific" },
);
console.log(Object.getOwnPropertyDescriptors(formatter));
// {
// [Symbol(IntlLegacyConstructedSymbol)]: {
// value: NumberFormat [Intl.NumberFormat] {},
// writable: false,
// enumerable: false,
// configurable: false
// }
// }
```
Note that there's only one actual `Intl.NumberFormat` instance here: the one hidden in `[Symbol(IntlLegacyConstructedSymbol)]`. Calling the [`format()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/format) and [`resolvedOptions()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/resolvedOptions) methods on `formatter` would correctly use the options stored in that instance, but calling all other methods (e.g. [`formatRange()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/formatRange)) would fail with "TypeError: formatRange method called on incompatible Object", because those methods don't consult the hidden instance's options.
This behavior, called `ChainNumberFormat`, does not happen when `Intl.NumberFormat()` is called without `new` but with `this` set to anything else that's not an `instanceof Intl.NumberFormat`. If you call it directly as `Intl.NumberFormat()`, the `this` value is [`Intl`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl), and a new `Intl.NumberFormat` instance is created normally.
### Exceptions
- {{jsxref("RangeError")}}
- : Thrown in one of the following cases:
- A property that takes enumerated values (such as `style`, `units`, `currency`, and so on) is set to an invalid value.
- Both `maximumFractionDigits` and `minimumFractionDigits` are set, and they are set to different values.
Note that depending on various formatting options, these properties can have default values.
It is therefore possible to get this error even if you only set one of the properties.
- {{jsxref("TypeError")}}
- : Thrown if the `options.style` property is set to "unit" or "currency", and no value has been set for the corresponding property `options.unit` or `options.currency`.
## Examples
### Basic usage
In basic use without specifying a locale, a formatted string in the default locale and with default options is returned.
```js
const amount = 3500;
console.log(new Intl.NumberFormat().format(amount));
// '3,500' if in US English locale
```
### Decimal and percent formatting
```js
const amount = 3500;
new Intl.NumberFormat("en-US", {
style: "decimal",
}).format(amount); // '3,500'
new Intl.NumberFormat("en-US", {
style: "percent",
}).format(amount); // '350,000%'
```
### Unit formatting
If the `style` is `'unit'`, a `unit` property must be provided.
Optionally, `unitDisplay` controls the unit formatting.
```js
const amount = 3500;
new Intl.NumberFormat("en-US", {
style: "unit",
unit: "liter",
}).format(amount); // '3,500 L'
new Intl.NumberFormat("en-US", {
style: "unit",
unit: "liter",
unitDisplay: "long",
}).format(amount); // '3,500 liters'
```
### Currency formatting
If the `style` is `'currency'`, a `currency` property
must be provided. Optionally, `currencyDisplay` and
`currencySign` control the unit formatting.
```js
const amount = -3500;
new Intl.NumberFormat("en-US", {
style: "currency",
currency: "USD",
}).format(amount); // '-$3,500.00'
new Intl.NumberFormat("bn", {
style: "currency",
currency: "USD",
currencyDisplay: "name",
}).format(amount); // '-3,500.00 US dollars'
new Intl.NumberFormat("bn", {
style: "currency",
currency: "USD",
currencySign: "accounting",
}).format(amount); // '($3,500.00)'
```
### Scientific, engineering or compact notations
Scientific and compact notation are represented by the `notation` option and can be formatted like this:
```js
new Intl.NumberFormat("en-US", {
notation: "scientific",
}).format(987654321);
// 9.877E8
new Intl.NumberFormat("pt-PT", {
notation: "scientific",
}).format(987654321);
// 9,877E8
new Intl.NumberFormat("en-GB", {
notation: "engineering",
}).format(987654321);
// 987.654E6
new Intl.NumberFormat("de", {
notation: "engineering",
}).format(987654321);
// 987,654E6
new Intl.NumberFormat("zh-CN", {
notation: "compact",
}).format(987654321);
// 9.9亿
new Intl.NumberFormat("fr", {
notation: "compact",
compactDisplay: "long",
}).format(987654321);
// 988 millions
new Intl.NumberFormat("en-GB", {
notation: "compact",
compactDisplay: "short",
}).format(987654321);
// 988M
```
### Displaying signs
Display a sign for positive and negative numbers, but not zero:
```js
new Intl.NumberFormat("en-US", {
style: "percent",
signDisplay: "exceptZero",
}).format(0.55);
// '+55%'
```
Note that when the currency sign is "accounting", parentheses might be used instead of a minus sign:
```js
new Intl.NumberFormat("bn", {
style: "currency",
currency: "USD",
currencySign: "accounting",
signDisplay: "always",
}).format(-3500);
// '($3,500.00)'
```
### FractionDigits, SignificantDigits and IntegerDigits
You can specify the minimum or maximum number of fractional, integer or significant digits to display when formatting a number.
> **Note:** If both significant and fractional digit limits are specified, then the actual formatting depends on the [`roundingPriority`](#roundingpriority).
#### Using FractionDigits and IntegerDigits
The integer and fraction digit properties indicate the number of digits to display before and after the decimal point, respectively.
If the value to display has fewer integer digits than specified, it will be left-padded with zeros to the expected number.
If it has fewer fractional digits, it will be right-padded with zeros.
Both cases are shown below:
```js
// Formatting adds zeros to display minimum integers and fractions
console.log(
new Intl.NumberFormat("en", {
minimumIntegerDigits: 3,
minimumFractionDigits: 4,
}).format(4.33),
);
// "004.3300"
```
If a value has more fractional digits than the specified maximum number, it will be rounded.
The _way_ that it is rounded depends on the [`roundingMode`](#roundingmode) property (more details are provided in the [rounding modes](#rounding_modes) section).
Below the value is rounded from five fractional digits (`4.33145`) to two (`4.33`):
```js
// Display value shortened to maximum number of digits
console.log(
new Intl.NumberFormat("en", {
maximumFractionDigits: 2,
}).format(4.33145),
);
// "4.33"
```
The minimum fractional digits have no effect if the value already has more than 2 fractional digits:
```js
// Minimum fractions have no effect if value is higher precision.
console.log(
new Intl.NumberFormat("en", {
minimumFractionDigits: 2,
}).format(4.33145),
);
// "4.331"
```
> **Warning:** Watch out for default values as they may affect formatting even if not specified in your code.
> The default maximum digit value is `3` for plain values, `2` for currency, and may have different values for other predefined types.
The formatted value above is rounded to 3 digits, even though we didn't specify the maximum digits!
This is because a default value of `maximumFractionDigits` is set when we specify `minimumFractionDigits`, and visa versa. The default values of `maximumFractionDigits` and `minimumFractionDigits` are `3` and `0`, respectively.
You can use [`resolvedOptions()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/resolvedOptions) to inspect the formatter.
```js
console.log(
new Intl.NumberFormat("en", {
maximumFractionDigits: 2,
}).resolvedOptions(),
);
// {
// …
// minimumIntegerDigits: 1,
// minimumFractionDigits: 0,
// maximumFractionDigits: 2,
// …
// }
console.log(
new Intl.NumberFormat("en", {
minimumFractionDigits: 2,
}).resolvedOptions(),
);
// {
// …
// minimumIntegerDigits: 1,
// minimumFractionDigits: 2,
// maximumFractionDigits: 3,
// …
// }
```
#### Using SignificantDigits
The number of _significant digits_ is the total number of digits including both integer and fractional parts.
The `maximumSignificantDigits` is used to indicate the total number of digits from the original value to display.
The examples below show how this works.
Note in particular the last case: only the first digit is retained and the others are discarded/set to zero.
```js
// Display 5 significant digits
console.log(
new Intl.NumberFormat("en", {
maximumSignificantDigits: 5,
}).format(54.33145),
);
// "54.331"
// Max 2 significant digits
console.log(
new Intl.NumberFormat("en", {
maximumSignificantDigits: 2,
}).format(54.33145),
);
// "54"
// Max 1 significant digits
console.log(
new Intl.NumberFormat("en", {
maximumSignificantDigits: 1,
}).format(54.33145),
);
// "50"
```
The `minimumSignificantDigits` ensures that at least the specified number of digits are displayed, adding zeros to the end of the value if needed.
```js
// Minimum 10 significant digits
console.log(
new Intl.NumberFormat("en", {
minimumSignificantDigits: 10,
}).format(54.33145),
);
// "54.33145000"
```
> **Warning:** Watch out for default values as they may affect formatting.
> If only one `SignificantDigits` property is used, then its counterpart will automatically be applied with the default value.
> The default maximum and minimum significant digit values are 20 and 1, respectively.
#### Specifying significant and fractional digits at the same time
The fraction digits ([`minimumFractionDigits`](#minimumfractiondigits)/[`maximumFractionDigits`](#maximumfractiondigits)) and significant digits ([`minimumSignificantDigits`](#minimumsignificantdigits)/[`maximumSignificantDigits`](#maximumsignificantdigits)) are both ways of controlling how many fractional and leading digits should be formatted.
If both are used at the same time, it is possible for them to conflict.
These conflicts are resolved using the [`roundingPriority`](#roundingpriority) property.
By default, this has a value of `"auto"`, which means that if either [`minimumSignificantDigits`](#minimumsignificantdigits) or [`maximumSignificantDigits`](#minimumsignificantdigits) is specified, the fractional and integer digit properties will be ignored.
For example, the code below formats the value of `4.33145` with `maximumFractionDigits: 3`, and then `maximumSignificantDigits: 2`, and then both.
The value with both is the one set with `maximumSignificantDigits`.
```js
console.log(
new Intl.NumberFormat("en", {
maximumFractionDigits: 3,
}).format(4.33145),
);
// "4.331"
console.log(
new Intl.NumberFormat("en", {
maximumSignificantDigits: 2,
}).format(4.33145),
);
// "4.3"
console.log(
new Intl.NumberFormat("en", {
maximumFractionDigits: 3,
maximumSignificantDigits: 2,
}).format(4.33145),
);
// "4.3"
```
Using [`resolvedOptions()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/resolvedOptions) to inspect the formatter, we can see that the returned object does not include `maximumFractionDigits` when `maximumSignificantDigits` or `minimumSignificantDigits` are specified.
```js
console.log(
new Intl.NumberFormat("en", {
maximumFractionDigits: 3,
maximumSignificantDigits: 2,
}).resolvedOptions(),
);
// {
// …
// minimumIntegerDigits: 1,
// minimumSignificantDigits: 1,
// maximumSignificantDigits: 2,
// …
// }
console.log(
new Intl.NumberFormat("en", {
maximumFractionDigits: 3,
minimumSignificantDigits: 2,
}).resolvedOptions(),
);
// {
// …
// minimumIntegerDigits: 1,
// minimumSignificantDigits: 2,
// maximumSignificantDigits: 21,
// …
// }
```
In addition to `"auto"`, you can resolve conflicts by specifying [`roundingPriority`](#roundingpriority) as `"morePrecision"` or `"lessPrecision"`.
The formatter calculates the precision using the values of `maximumSignificantDigits` and `maximumFractionDigits`.
The code below shows the format being selected for the three different rounding priorities:
```js
const maxFracNF = new Intl.NumberFormat("en", {
maximumFractionDigits: 3,
});
console.log(`maximumFractionDigits:3 - ${maxFracNF.format(1.23456)}`);
// "maximumFractionDigits:2 - 1.235"
const maxSigNS = new Intl.NumberFormat("en", {
maximumSignificantDigits: 3,
});
console.log(`maximumSignificantDigits:3 - ${maxSigNS.format(1.23456)}`);
// "maximumSignificantDigits:3 - 1.23"
const bothAuto = new Intl.NumberFormat("en", {
maximumSignificantDigits: 3,
maximumFractionDigits: 3,
});
console.log(`auto - ${bothAuto.format(1.23456)}`);
// "auto - 1.23"
const bothLess = new Intl.NumberFormat("en", {
roundingPriority: "lessPrecision",
maximumSignificantDigits: 3,
maximumFractionDigits: 3,
});
console.log(`lessPrecision - ${bothLess.format(1.23456)}`);
// "lessPrecision - 1.23"
const bothMore = new Intl.NumberFormat("en", {
roundingPriority: "morePrecision",
maximumSignificantDigits: 3,
maximumFractionDigits: 3,
});
console.log(`morePrecision - ${bothMore.format(1.23456)}`);
// "morePrecision - 1.235"
```
Note that the algorithm can behave in an unintuitive way if a minimum value is specified without a maximum value.
The example below formats the value `1` specifying `minimumFractionDigits: 2` (formatting to `1.00`) and `minimumSignificantDigits: 2` (formatting to `1.0`).
Since `1.00` has more digits than `1.0`, this should be the result when prioritizing `morePrecision`, but in fact the opposite is true:
```js
const bothLess = new Intl.NumberFormat("en", {
roundingPriority: "lessPrecision",
minimumFractionDigits: 2,
minimumSignificantDigits: 2,
});
console.log(`lessPrecision - ${bothLess.format(1)}`);
// "lessPrecision - 1.00"
const bothMore = new Intl.NumberFormat("en", {
roundingPriority: "morePrecision",
minimumFractionDigits: 2,
minimumSignificantDigits: 2,
});
console.log(`morePrecision - ${bothMore.format(1)}`);
// "morePrecision - 1.0"
```
The reason for this is that only the "maximum precision" values are used for the calculation, and the default value of `maximumSignificantDigits` is much higher than `maximumFractionDigits`.
> **Note:** The working group have proposed a modification of the algorithm where the formatter should evaluate the result of using the specified fractional and significant digits independently (taking account of both minimum and maximum values).
> It will then select the option that displays more fractional digits if `morePrecision` is set, and fewer if `lessPrecision` is set.
> This will result in more intuitive behavior for this case.
### Rounding modes
If a value has more fractional digits than allowed by the constructor options, the formatted value will be _rounded_ to the specified number of fractional digits.
The _way_ in which the value is rounded depends on the [`roundingMode`](#roundingmode) property.
Number formatters use `halfExpand` rounding by default, which rounds values "away from zero" at the half-increment (in other words, the _magnitude_ of the value is rounded up).
For a positive number, if the fractional digits to be removed are closer to the next increment (or on the half way point) then the remaining fractional digits will be rounded up, otherwise they are rounded down.
This is shown below: 2.23 rounded to two significant digits is truncated to 2.2 because 2.23 is less than the half increment 2.25, while values of 2.25 and greater are rounded up to 2.3:
```js
// Value below half-increment: round down.
console.log(
new Intl.NumberFormat("en", {
maximumSignificantDigits: 2,
}).format(2.23),
);
// "2.2"
// Value on or above half-increment: round up.
console.log(
new Intl.NumberFormat("en", {
maximumSignificantDigits: 2,
}).format(2.25),
);
console.log(
new Intl.NumberFormat("en", {
maximumSignificantDigits: 2,
}).format(2.28),
);
// "2.3"
// "2.3"
```
A negative number on or below the half-increment point is also rounded away from zero (becomes more negative):
```js
// Value below half-increment: round down.
console.log(
new Intl.NumberFormat("en", {
maximumSignificantDigits: 2,
}).format(-2.23),
);
// "-2.2"
// Value on or above half-increment: round up.
console.log(
new Intl.NumberFormat("en", {
maximumSignificantDigits: 2,
}).format(-2.25),
);
console.log(
new Intl.NumberFormat("en", {
maximumSignificantDigits: 2,
}).format(-2.28),
);
// "-2.3"
// "-2.3"
```
The table below show the effect of different rounding modes for positive and negative values that are on and around the half-increment.
| rounding mode | 2.23 | 2.25 | 2.28 | -2.23 | -2.25 | -2.28 |
| ------------- | ---- | ---- | ---- | ----- | ----- | ----- |
| `ceil` | 2.3 | 2.3 | 2.3 | -2.2 | -2.2 | -2.2 |
| `floor` | 2.2 | 2.2 | 2.2 | -2.3 | -2.3 | -2.3 |
| `expand` | 2.3 | 2.3 | 2.3 | -2.3 | -2.3 | -2.3 |
| `trunc` | 2.2 | 2.2 | 2.2 | -2.2 | -2.2 | -2.2 |
| `halfCeil` | 2.2 | 2.3 | 2.3 | -2.2 | -2.2 | -2.3 |
| `halfFloor` | 2.2 | 2.2 | 2.3 | -2.2 | -2.3 | -2.3 |
| `halfExpand` | 2.2 | 2.3 | 2.3 | -2.2 | -2.3 | -2.3 |
| `halfTrunc` | 2.2 | 2.2 | 2.3 | -2.2 | -2.2 | -2.3 |
| `halfEven` | 2.2 | 2.2 | 2.3 | -2.2 | -2.2 | -2.3 |
When using `halfEven`, its behavior also depends on the parity (odd or even) of the last digit of the rounded number. For example, the behavior of `halfEven` in the table above is the same as `halfTrunc`, because the magnitudes of all numbers are between a smaller "even" number (2.2) and a larger "odd" number (2.3). If the numbers are between ±2.3 and ±2.4, `halfEven` will behave like `halfExpand` instead. This behavior avoids consistently under- or over-estimating half-increments in a large data sample.
### Using roundingIncrement
Sometimes we want to round the remaining fractional digits to some other increment than the next integer.
For example, currencies for which the smallest coin is 5 cents might want to round the value to increments of 5, reflecting amounts that can actually be paid in cash.
This kind of rounding can be achieved with the [`roundingIncrement`](#roundingincrement) property.
For example, if `maximumFractionDigits` is 2 and `roundingIncrement` is 5, then the number is rounded to the nearest 0.05:
```js
const nf = new Intl.NumberFormat("en-US", {
style: "currency",
currency: "USD",
maximumFractionDigits: 2,
roundingIncrement: 5,
});
console.log(nf.format(11.29)); // "$11.30"
console.log(nf.format(11.25)); // "$11.25"
console.log(nf.format(11.22)); // "$11.20"
```
This particular pattern is referred to as "nickel rounding", where nickel is the colloquial name for a USA 5 cent coin.
To round to the nearest 10 cents ("dime rounding"), you could change `roundingIncrement` to `10`.
```js
const nf = new Intl.NumberFormat("en-US", {
style: "currency",
currency: "USD",
maximumFractionDigits: 2,
roundingIncrement: 5,
});
console.log(nf.format(11.29)); // "$11.30"
console.log(nf.format(11.25)); // "$11.25"
console.log(nf.format(11.22)); // "$11.20"
```
You can also use [`roundingMode`](#roundingmode) to change the rounding algorithm.
The example below shows how `halfCeil` rounding can be used to round the value "less positive" below the half-rounding increment and "more positive" if above or on the half-increment.
The incremented digit is "0.05" so the half-increment is at .025 (below, this is shown at 11.225).
```js
const nf = new Intl.NumberFormat("en-US", {
style: "currency",
currency: "USD",
maximumFractionDigits: 2,
roundingIncrement: 5,
roundingMode: "halfCeil",
});
console.log(nf.format(11.21)); // "$11.20"
console.log(nf.format(11.22)); // "$11.20"
console.log(nf.format(11.224)); // "$11.20"
console.log(nf.format(11.225)); // "$11.25"
console.log(nf.format(11.23)); // "$11.25"
```
If you need to change the number of digits, remember that `minimumFractionDigits` and `maximumFractionDigits` must both be set to the same value, or a `RangeError` is thrown.
`roundingIncrement` cannot be mixed with significant-digits rounding or any setting of `roundingPriority` other than `auto`.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Intl.NumberFormat")}}
- {{jsxref("Intl.supportedValuesOf()")}}
- {{jsxref("Intl")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/numberformat | data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/numberformat/supportedlocalesof/index.md | ---
title: Intl.NumberFormat.supportedLocalesOf()
slug: Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/supportedLocalesOf
page-type: javascript-static-method
browser-compat: javascript.builtins.Intl.NumberFormat.supportedLocalesOf
---
{{JSRef}}
The **`Intl.NumberFormat.supportedLocalesOf()`** static method returns an array containing those of the provided locales that are supported in number formatting without having to fall back to the runtime's default locale.
{{EmbedInteractiveExample("pages/js/intl-numberformat-supportedlocalesof.html", "shorter")}}
## Syntax
```js-nolint
Intl.NumberFormat.supportedLocalesOf(locales)
Intl.NumberFormat.supportedLocalesOf(locales, options)
```
### Parameters
- `locales`
- : A string with a BCP 47 language tag, or an array of such strings. For the general form and interpretation of the `locales` argument, see [the parameter description on the `Intl` main page](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#locales_argument).
- `options` {{optional_inline}}
- : An object that may have the following property:
- `localeMatcher`
- : The locale matching algorithm to use. Possible values are `"lookup"` and `"best fit"`; the default is `"best fit"`. For information about this option, see the {{jsxref("Intl", "Intl", "#locale_identification_and_negotiation", 1)}} page.
### Return value
An array of strings representing a subset of the given locale tags that are supported in number formatting without having to fall back to the runtime's default locale.
## Examples
### Using supportedLocalesOf()
Assuming a runtime that supports Indonesian and German but not Balinese in number formatting, `supportedLocalesOf` returns the Indonesian and German language tags unchanged, even though `pinyin` collation is neither relevant to number formatting nor used with Indonesian, and a specialized German for Indonesia is unlikely to be supported. Note the specification of the `"lookup"` algorithm here — a `"best fit"` matcher might decide that Indonesian is an adequate match for Balinese since most Balinese speakers also understand Indonesian, and therefore return the Balinese language tag as well.
```js
const locales = ["ban", "id-u-co-pinyin", "de-ID"];
const options = { localeMatcher: "lookup" };
console.log(Intl.NumberFormat.supportedLocalesOf(locales, options));
// ["id-u-co-pinyin", "de-ID"]
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Intl.NumberFormat")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl | data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/getcanonicallocales/index.md | ---
title: Intl.getCanonicalLocales()
slug: Web/JavaScript/Reference/Global_Objects/Intl/getCanonicalLocales
page-type: javascript-static-method
browser-compat: javascript.builtins.Intl.getCanonicalLocales
---
{{JSRef}}
The **`Intl.getCanonicalLocales()`** static method returns an array
containing the canonical locale names. Duplicates will be omitted and elements will be
validated as structurally valid language tags.
{{EmbedInteractiveExample("pages/js/intl-getcanonicallocales.html")}}
## Syntax
```js-nolint
Intl.getCanonicalLocales(locales)
```
### Parameters
- `locales`
- : A list of {{jsxref("String")}} values for which to get the canonical locale names.
### Return value
An array containing the canonical locale names.
## Examples
### Using getCanonicalLocales
```js
Intl.getCanonicalLocales("EN-US"); // ["en-US"]
Intl.getCanonicalLocales(["EN-US", "Fr"]); // ["en-US", "fr"]
Intl.getCanonicalLocales("EN_US");
// RangeError:'EN_US' is not a structurally valid language tag
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- [Polyfill of `Intl.getCanonicalLocales` in FormatJS](https://formatjs.io/docs/polyfills/intl-getcanonicallocales/)
- {{jsxref("Intl/NumberFormat/supportedLocalesOf", "Intl.NumberFormat.supportedLocalesOf()")}}
- {{jsxref("Intl/DateTimeFormat/supportedLocalesOf", "Intl.DateTimeFormat.supportedLocalesOf()")}}
- {{jsxref("Intl/Collator/supportedLocalesOf", "Intl.Collator.supportedLocalesOf()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl | data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/collator/index.md | ---
title: Intl.Collator
slug: Web/JavaScript/Reference/Global_Objects/Intl/Collator
page-type: javascript-class
browser-compat: javascript.builtins.Intl.Collator
---
{{JSRef}}
The **`Intl.Collator`** object enables language-sensitive string comparison.
{{EmbedInteractiveExample("pages/js/intl-collator.html")}}
## Constructor
- {{jsxref("Intl/Collator/Collator", "Intl.Collator()")}}
- : Creates a new `Collator` object.
## Static methods
- {{jsxref("Intl/Collator/supportedLocalesOf", "Intl.Collator.supportedLocalesOf()")}}
- : Returns an array containing those of the provided locales that are supported without having to fall back to the runtime's default locale.
## Instance properties
These properties are defined on `Intl.Collator.prototype` and shared by all `Intl.Collator` instances.
- {{jsxref("Object/constructor", "Intl.Collator.prototype.constructor")}}
- : The constructor function that created the instance object. For `Intl.Collator` instances, the initial value is the {{jsxref("Intl/Collator/Collator", "Intl.Collator")}} constructor.
- `Intl.Collator.prototype[@@toStringTag]`
- : The initial value of the [`@@toStringTag`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/toStringTag) property is the string `"Intl.Collator"`. This property is used in {{jsxref("Object.prototype.toString()")}}.
## Instance methods
- {{jsxref("Intl/Collator/compare", "Intl.Collator.prototype.compare()")}}
- : Getter function that compares two strings according to the sort order of this {{jsxref("Intl.Collator")}} object.
- {{jsxref("Intl/Collator/resolvedOptions", "Intl.Collator.prototype.resolvedOptions()")}}
- : Returns a new object with properties reflecting the locale and collation options computed during initialization of the object.
## Examples
### Using Collator
The following example demonstrates the different potential results for a string occurring before, after, or at the same level as another:
```js
console.log(new Intl.Collator().compare("a", "c")); // -1, or some other negative value
console.log(new Intl.Collator().compare("c", "a")); // 1, or some other positive value
console.log(new Intl.Collator().compare("a", "a")); // 0
```
Note that the results shown in the code above can vary between browsers and browser versions. This is because the values are implementation-specific. That is, the specification requires only that the before and after values are negative and positive.
### Using locales
The results provided by [`Intl.Collator.prototype.compare()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator/compare) vary between languages. In order to get the sort order of the language used in the user interface of your application, make sure to specify that language (and possibly some fallback languages) using the `locales` argument:
```js
// in German, ä sorts with a
console.log(new Intl.Collator("de").compare("ä", "z"));
// -1, or some other negative value
// in Swedish, ä sorts after z
console.log(new Intl.Collator("sv").compare("ä", "z"));
// 1, or some other positive value
```
### Using options
The results provided by [`Intl.Collator.prototype.compare()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator/compare) can be customized using the `options` argument:
```js
// in German, ä has a as the base letter
console.log(new Intl.Collator("de", { sensitivity: "base" }).compare("ä", "a"));
// 0
// in Swedish, ä and a are separate base letters
console.log(new Intl.Collator("sv", { sensitivity: "base" }).compare("ä", "a"));
// 1, or some other positive value
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Intl")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/collator | data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/collator/resolvedoptions/index.md | ---
title: Intl.Collator.prototype.resolvedOptions()
slug: Web/JavaScript/Reference/Global_Objects/Intl/Collator/resolvedOptions
page-type: javascript-instance-method
browser-compat: javascript.builtins.Intl.Collator.resolvedOptions
---
{{JSRef}}
The **`resolvedOptions()`** method of {{jsxref("Intl.Collator")}} instances returns a new object with properties reflecting the locale and collation options
computed during initialization of this collator object.
{{EmbedInteractiveExample("pages/js/intl-collator-prototype-resolvedoptions.html")}}
## Syntax
```js-nolint
resolvedOptions()
```
### Parameters
None.
### Return value
A new object with properties reflecting the locale and collation options computed
during the initialization of the given {{jsxref("Intl.Collator")}} object.
## Description
The resulting object has the following properties:
- `locale`
- : The BCP 47 language tag for the locale actually used. If any Unicode extension
values were requested in the input BCP 47 language tag that led to this locale,
the key-value pairs that were requested and are supported for this locale are
included in `locale`.
- `usage`, `sensitivity`, `ignorePunctuation`
- : The values provided for these properties in the `options` argument or
filled in as defaults.
- `collation`
- : The value requested using the Unicode extension key `"co"`, if it is
supported for `locale`, or `"default"`.
- `numeric`, `caseFirst`
- : The values requested for these properties in the `options` argument or
using the Unicode extension keys `"kn"` and `"kf"` or filled
in as defaults. If the implementation does not support these properties, they are
omitted.
## Examples
### Using the resolvedOptions method
```js
const de = new Intl.Collator("de", { sensitivity: "base" });
const usedOptions = de.resolvedOptions();
usedOptions.locale; // "de"
usedOptions.usage; // "sort"
usedOptions.sensitivity; // "base"
usedOptions.ignorePunctuation; // false
usedOptions.collation; // "default"
usedOptions.numeric; // false
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Intl.Collator")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/collator | data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/collator/compare/index.md | ---
title: Intl.Collator.prototype.compare()
slug: Web/JavaScript/Reference/Global_Objects/Intl/Collator/compare
page-type: javascript-instance-method
browser-compat: javascript.builtins.Intl.Collator.compare
---
{{JSRef}}
The **`compare()`** method of {{jsxref("Intl.Collator")}} instances compares two
strings according to the sort order of this collator object.
{{EmbedInteractiveExample("pages/js/intl-collator-prototype-compare.html")}}
## Syntax
```js-nolint
compare(string1, string2)
```
### Parameters
- `string1`, `string2`
- : The strings to compare against each other.
### Return value
A number indicating how `string1` and `string2` compare to each other according to the sort order of this {{jsxref("Intl.Collator")}} object:
- A negative value if `string1` comes before `string2`;
- A positive value if `string1` comes after `string2`;
- 0 if they are considered equal.
## Examples
### Using compare for array sort
Use the `compare` function for sorting arrays. Note that the function
is bound to the collator from which it was obtained, so it can be passed directly to
{{jsxref("Array.prototype.sort()")}}.
```js
const a = ["Offenbach", "Österreich", "Odenwald"];
const collator = new Intl.Collator("de-u-co-phonebk");
a.sort(collator.compare);
console.log(a.join(", ")); // "Odenwald, Österreich, Offenbach"
```
### Using compare for array search
Use the `compare` function for finding matching strings in arrays:
```js
const a = ["Congrès", "congres", "Assemblée", "poisson"];
const collator = new Intl.Collator("fr", {
usage: "search",
sensitivity: "base",
});
const s = "congres";
const matches = a.filter((v) => collator.compare(v, s) === 0);
console.log(matches.join(", ")); // "Congrès, congres"
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Intl.Collator")}}
- {{jsxref("String.prototype.localeCompare()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/collator | data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/collator/collator/index.md | ---
title: Intl.Collator() constructor
slug: Web/JavaScript/Reference/Global_Objects/Intl/Collator/Collator
page-type: javascript-constructor
browser-compat: javascript.builtins.Intl.Collator.Collator
---
{{JSRef}}
The **`Intl.Collator()`** constructor creates {{jsxref("Intl.Collator")}} objects.
{{EmbedInteractiveExample("pages/js/intl-collator.html")}}
## Syntax
```js-nolint
new Intl.Collator()
new Intl.Collator(locales)
new Intl.Collator(locales, options)
Intl.Collator()
Intl.Collator(locales)
Intl.Collator(locales, options)
```
> **Note:** `Intl.Collator()` can be called with or without [`new`](/en-US/docs/Web/JavaScript/Reference/Operators/new). Both create a new `Intl.Collator` instance.
### Parameters
- `locales` {{optional_inline}}
- : A string with a BCP 47 language tag or an {{jsxref("Intl.Locale")}} instance, or an array of such locale identifiers. For the general form and interpretation of the `locales` argument, see [the parameter description on the `Intl` main page](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#locales_argument).
The following Unicode extension keys are allowed:
- `co`
- : See [`collation`](#collation).
- `kn`
- : See [`numeric`](#numeric).
- `kf`
- : See [`caseFirst`](#casefirst).
These keys can also be set with `options` (as listed below). When both are set, the `options` property takes precedence.
- `options` {{optional_inline}}
- : An object containing the following properties, in the order they are retrieved (all of them are optional):
- `usage`
- : Whether the comparison is for sorting a list of strings or fuzzy (for the Latin script diacritic-insensitive and case-insensitive) filtering a list of strings by key. Possible values are:
- `"sort"` (default)
- : For sorting a list of strings.
- `"search"`
- : For filtering a list of strings by testing each list item for a full-string match against a key. With `"search"`, the caller should only pay attention to whether `compare()` returns zero or non-zero and should not distinguish the non-zero return values from each other. That is, it is inappropriate to use `"search"` for sorting/ordering.
- `localeMatcher`
- : The locale matching algorithm to use. Possible values are `"lookup"` and `"best fit"`; the default is `"best fit"`. For information about this option, see [Locale identification and negotiation](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#locale_identification_and_negotiation).
- `collation`
- : Variant collations for certain locales, such as `"emoji"`, `"pinyin"`, `"stroke"`, and so on. For a list of supported collation types, see [`Intl.Locale.prototype.getCollations()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Locale/getCollations#supported_collation_types); the default is `"default"`. This option can also be set through the `co` Unicode extension key; if both are provided, this `options` property takes precedence.
- `numeric`
- : Whether numeric collation should be used, such that "1" < "2" < "10". Possible values are `true` and `false`; the default is `false`. This option can also be set through the `kn` Unicode extension key; if both are provided, this `options` property takes precedence.
- `caseFirst`
- : Whether upper case or lower case should sort first. Possible values are `"upper"`, `"lower"`, and `"false"` (use the locale's default); the default is `"false"`. This option can also be set through the `kf` Unicode extension key; if both are provided, this `options` property takes precedence.
- `sensitivity`
- : Which differences in the strings should lead to non-zero result values. Possible values are:
- `"base"`
- : Only strings that differ in base letters compare as unequal. Examples: a ≠ b, a = á, a = A.
- `"accent"`
- : Only strings that differ in base letters or accents and other diacritic marks compare as unequal. Examples: a ≠ b, a ≠ á, a = A.
- `"case"`
- : Only strings that differ in base letters or case compare as unequal. Examples: a ≠ b, a = á, a ≠ A.
- `"variant"`
- : Strings that differ in base letters, accents and other diacritic marks, or case compare as unequal. Other differences may also be taken into consideration. Examples: a ≠ b, a ≠ á, a ≠ A.
The default is `"variant"` for usage `"sort"`; it's locale dependent for usage `"search"` per spec, but the core functionality of `"search"` is accent-insensitive and case-insensitive filtering, so `"base"` makes the most sense (and perhaps `"case"`).
- `ignorePunctuation`
- : Whether punctuation should be ignored. Possible values are `true` and `false`; the default is `false`.
### Exceptions
- {{jsxref("RangeError")}}
- : Thrown if `locales` or `options` contain invalid values.
## Examples
### Using Collator
The following example demonstrates the different potential results for a string
occurring before, after, or at the same level as another:
```js
console.log(new Intl.Collator().compare("a", "c")); // -1, or some other negative value
console.log(new Intl.Collator().compare("c", "a")); // 1, or some other positive value
console.log(new Intl.Collator().compare("a", "a")); // 0
```
Note that the results shown in the code above can vary between browsers and browser
versions. This is because the values are implementation-specific. That is, the
specification requires only that the before and after values are negative and
positive.
When usage is `"search"`, the caller should only pay attention to whether the return value of `compare()` is zero or non-zero. It is inappropriate to use a `Collator` with usage `"search"` for sorting.
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Intl.Collator")}}
- {{jsxref("Intl")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/collator | data/mdn-content/files/en-us/web/javascript/reference/global_objects/intl/collator/supportedlocalesof/index.md | ---
title: Intl.Collator.supportedLocalesOf()
slug: Web/JavaScript/Reference/Global_Objects/Intl/Collator/supportedLocalesOf
page-type: javascript-static-method
browser-compat: javascript.builtins.Intl.Collator.supportedLocalesOf
---
{{JSRef}}
The **`Intl.Collator.supportedLocalesOf()`** static method returns an array containing those of the provided locales that are supported in collation without having to fall back to the runtime's default locale.
{{EmbedInteractiveExample("pages/js/intl-collator-supportedlocalesof.html", "shorter")}}
## Syntax
```js-nolint
Intl.Collator.supportedLocalesOf(locales)
Intl.Collator.supportedLocalesOf(locales, options)
```
### Parameters
- `locales`
- : A string with a BCP 47 language tag, or an array of such strings. For the general form and interpretation of the `locales` argument, see [the parameter description on the `Intl` main page](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#locales_argument).
- `options` {{optional_inline}}
- : An object that may have the following property:
- `localeMatcher`
- : The locale matching algorithm to use. Possible values are `"lookup"` and `"best fit"`; the default is `"best fit"`. For information about this option, see the {{jsxref("Intl", "Intl", "#locale_identification_and_negotiation", 1)}} page.
### Return value
An array of strings representing a subset of the given locale tags that are supported in collation without having to fall back to the runtime's default locale.
## Examples
### Using supportedLocalesOf()
Assuming a runtime that supports Indonesian and German but not Balinese in collation, `supportedLocalesOf` returns the Indonesian and German language tags unchanged, even though `pinyin` collation is not used with Indonesian, and a specialized German for Indonesia is unlikely to be supported. Note the specification of the `"lookup"` algorithm here — a `"best fit"` matcher might decide that Indonesian is an adequate match for Balinese since most Balinese speakers also understand Indonesian, and therefore return the Balinese language tag as well.
```js
const locales = ["ban", "id-u-co-pinyin", "de-ID"];
const options = { localeMatcher: "lookup" };
console.log(Intl.Collator.supportedLocalesOf(locales, options));
// ["id-u-co-pinyin", "de-ID"]
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Intl.Collator")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects | data/mdn-content/files/en-us/web/javascript/reference/global_objects/weakref/index.md | ---
title: WeakRef
slug: Web/JavaScript/Reference/Global_Objects/WeakRef
page-type: javascript-class
browser-compat: javascript.builtins.WeakRef
---
{{JSRef}}
A **`WeakRef`** object lets you hold a weak reference to another object, without preventing that object from getting garbage-collected.
## Description
A `WeakRef` object contains a weak reference to an object, which is called its _target_ or _referent_. A _weak reference_ to an object is a reference that does not prevent the object from being reclaimed by the garbage collector. In contrast, a normal (or _strong_) reference keeps an object in memory. When an object no longer has any strong references to it, the JavaScript engine's garbage collector may destroy the object and reclaim its memory. If that happens, you can't get the object from a weak reference anymore.
Because [non-registered symbols](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol#shared_symbols_in_the_global_symbol_registry) are also garbage collectable, they can also be used as the target of a `WeakRef` object. However, the use case of this is limited.
### Avoid where possible
Correct use of `WeakRef` takes careful thought, and it's best avoided if possible. It's also important to avoid relying on any specific behaviors not guaranteed by the specification. When, how, and whether garbage collection occurs is down to the implementation of any given JavaScript engine. Any behavior you observe in one engine may be different in another engine, in another version of the same engine, or even in a slightly different situation with the same version of the same engine. Garbage collection is a hard problem that JavaScript engine implementers are constantly refining and improving their solutions to.
Here are some specific points included by the authors in the [proposal](https://github.com/tc39/proposal-weakrefs) that introduced `WeakRef`:
> [Garbage collectors](<https://en.wikipedia.org/wiki/Garbage_collection_(computer_science)>) are complicated. If an application or library depends on GC cleaning up a WeakRef or calling a finalizer \[cleanup callback] in a timely, predictable manner, it's likely to be disappointed: the cleanup may happen much later than expected, or not at all. Sources of variability include:
>
> - One object might be garbage-collected much sooner than another object, even if they become unreachable at the same time, e.g., due to generational collection.
> - Garbage collection work can be split up over time using incremental and concurrent techniques.
> - Various runtime heuristics can be used to balance memory usage, responsiveness.
> - The JavaScript engine may hold references to things which look like they are unreachable (e.g., in closures, or inline caches).
> - Different JavaScript engines may do these things differently, or the same engine may change its algorithms across versions.
> - Complex factors may lead to objects being held alive for unexpected amounts of time, such as use with certain APIs.
### Notes on WeakRefs
- If your code has just created a `WeakRef` for a target object, or has gotten a target object from a `WeakRef`'s `deref` method, that target object will not be reclaimed until the end of the current JavaScript [job](https://tc39.es/ecma262/multipage/executable-code-and-execution-contexts.html#job) (including any promise reaction jobs that run at the end of a script job). That is, you can only "see" an object get reclaimed between turns of the event loop. This is primarily to avoid making the behavior of any given JavaScript engine's garbage collector apparent in code — because if it were, people would write code relying on that behavior, which would break when the garbage collector's behavior changed. (Garbage collection is a hard problem; JavaScript engine implementers are constantly refining and improving how it works.)
- If multiple `WeakRef`s have the same target, they're consistent with one another. The result of calling `deref` on one of them will match the result of calling `deref` on another of them (in the same job), you won't get the target object from one of them but `undefined` from another.
- If the target of a `WeakRef` is also in a {{jsxref("FinalizationRegistry")}}, the `WeakRef`'s target is cleared at the same time or before any cleanup callback associated with the registry is called; if your cleanup callback calls `deref` on a `WeakRef` for the object, it will receive `undefined`.
- You cannot change the target of a `WeakRef`, it will always only ever be the original target object or `undefined` when that target has been reclaimed.
- A `WeakRef` might never return `undefined` from `deref`, even if nothing strongly holds the target, because the garbage collector may never decide to reclaim the object.
## Constructor
- {{jsxref("WeakRef/WeakRef", "WeakRef()")}}
- : Creates a new `WeakRef` object.
## Instance properties
These properties are defined on `WeakRef.prototype` and shared by all `WeakRef` instances.
- {{jsxref("Object/constructor", "WeakRef.prototype.constructor")}} {{optional_inline}}
- : The constructor function that created the instance object. For `WeakRef` instances, the initial value is the {{jsxref("WeakRef/WeakRef", "WeakRef")}} constructor.
> **Note:** This property is marked as "normative optional" in the specification, which means a conforming implementation may not expose the `constructor` property. This prevents arbitrary code from obtaining the `WeakRef` constructor and being able to observe garbage collection. However, all major engines do expose it by default.
- `WeakRef.prototype[@@toStringTag]`
- : The initial value of the [`@@toStringTag`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/toStringTag) property is the string `"WeakRef"`. This property is used in {{jsxref("Object.prototype.toString()")}}.
## Instance methods
- {{jsxref("WeakRef.prototype.deref()")}}
- : Returns the `WeakRef` object's target object, or `undefined` if the target object has been reclaimed.
## Examples
### Using a WeakRef object
This example starts a counter shown in a DOM element, stopping when the element doesn't exist anymore:
```js
class Counter {
constructor(element) {
// Remember a weak reference to the DOM element
this.ref = new WeakRef(element);
this.start();
}
start() {
if (this.timer) {
return;
}
this.count = 0;
const tick = () => {
// Get the element from the weak reference, if it still exists
const element = this.ref.deref();
if (element) {
element.textContent = ++this.count;
} else {
// The element doesn't exist anymore
console.log("The element is gone.");
this.stop();
this.ref = null;
}
};
tick();
this.timer = setInterval(tick, 1000);
}
stop() {
if (this.timer) {
clearInterval(this.timer);
this.timer = 0;
}
}
}
const counter = new Counter(document.getElementById("counter"));
setTimeout(() => {
document.getElementById("counter").remove();
}, 5000);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("FinalizationRegistry")}}
- {{jsxref("WeakSet")}}
- {{jsxref("WeakMap")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/weakref | data/mdn-content/files/en-us/web/javascript/reference/global_objects/weakref/weakref/index.md | ---
title: WeakRef() constructor
slug: Web/JavaScript/Reference/Global_Objects/WeakRef/WeakRef
page-type: javascript-constructor
browser-compat: javascript.builtins.WeakRef.WeakRef
---
{{JSRef}}
The **`WeakRef()`** constructor creates {{jsxref("WeakRef")}} objects.
## Syntax
```js-nolint
new WeakRef(target)
```
> **Note:** `WeakRef()` can only be constructed with [`new`](/en-US/docs/Web/JavaScript/Reference/Operators/new). Attempting to call it without `new` throws a {{jsxref("TypeError")}}.
### Parameters
- `target`
- : The target value the WeakRef should refer to (also called the _referent_). Must be an object or a [non-registered symbol](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol#shared_symbols_in_the_global_symbol_registry).
### Return value
A new `WeakRef` object referring to the given target value.
### Exceptions
- {{jsxref("TypeError")}}
- : Thrown if `target` is not an object or a [non-registered symbol](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol#shared_symbols_in_the_global_symbol_registry).
## Examples
### Creating a new WeakRef object
See the main [`WeakRef`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakRef#examples)
page for a complete example.
```js
class Counter {
constructor(element) {
// Remember a weak reference to a DOM element
this.ref = new WeakRef(element);
this.start();
}
}
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("WeakRef")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/weakref | data/mdn-content/files/en-us/web/javascript/reference/global_objects/weakref/deref/index.md | ---
title: WeakRef.prototype.deref()
slug: Web/JavaScript/Reference/Global_Objects/WeakRef/deref
page-type: javascript-instance-method
browser-compat: javascript.builtins.WeakRef.deref
---
{{JSRef}}
The **`deref()`** method of {{jsxref("WeakRef")}} instances returns this `WeakRef`'s target value, or `undefined` if the target value has been garbage-collected.
## Syntax
```js-nolint
deref()
```
### Parameters
None.
### Return value
The target value of the WeakRef, which is either an object or a [non-registered symbol](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol#shared_symbols_in_the_global_symbol_registry). Returns `undefined` if the value has been garbage-collected.
## Description
See the [Notes on WeakRefs](/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakRef#notes_on_weakrefs) section of the {{jsxref("WeakRef")}} page for some important notes.
## Examples
### Using deref()
See the [Examples](/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakRef#examples)
section of the {{jsxref("WeakRef")}} page for the complete example.
```js
const tick = () => {
// Get the element from the weak reference, if it still exists
const element = this.ref.deref();
if (element) {
element.textContent = ++this.count;
} else {
// The element doesn't exist anymore
console.log("The element is gone.");
this.stop();
this.ref = null;
}
};
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("WeakRef")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects | data/mdn-content/files/en-us/web/javascript/reference/global_objects/date/index.md | ---
title: Date
slug: Web/JavaScript/Reference/Global_Objects/Date
page-type: javascript-class
browser-compat: javascript.builtins.Date
---
{{JSRef}}
JavaScript **`Date`** objects represent a single moment in time in a platform-independent format. `Date` objects encapsulate an integral number that represents milliseconds since the midnight at the beginning of January 1, 1970, UTC (the _epoch_).
> **Note:** TC39 is working on [Temporal](https://tc39.es/proposal-temporal/docs/index.html), a new Date/Time API. Read more about it on the [Igalia blog](https://blogs.igalia.com/compilers/2020/06/23/dates-and-times-in-javascript/). It is not yet ready for production use!
## Description
### The epoch, timestamps, and invalid date
A JavaScript date is fundamentally specified as the time in milliseconds that has elapsed since the [epoch](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-time-values-and-time-range), which is defined as the midnight at the beginning of January 1, 1970, UTC (equivalent to the [UNIX epoch](/en-US/docs/Glossary/Unix_time)). This timestamp is _timezone-agnostic_ and uniquely defines an instant in history.
> **Note:** While the time value at the heart of a Date object is UTC, the basic methods to fetch the date and time or its components all work in the local (i.e. host system) time zone and offset.
The maximum timestamp representable by a `Date` object is slightly smaller than the maximum safe integer ({{jsxref("Number.MAX_SAFE_INTEGER")}}, which is 9,007,199,254,740,991). A `Date` object can represent a maximum of ±8,640,000,000,000,000 milliseconds, or ±100,000,000 (one hundred million) days, relative to the epoch. This is the range from April 20, 271821 BC to September 13, 275760 AD. Any attempt to represent a time outside this range results in the `Date` object holding a timestamp value of [`NaN`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/NaN), which is an "Invalid Date".
```js
console.log(new Date(8.64e15).toString()); // "Sat Sep 13 275760 00:00:00 GMT+0000 (Coordinated Universal Time)"
console.log(new Date(8.64e15 + 1).toString()); // "Invalid Date"
```
There are various methods that allow you to interact with the timestamp stored in the date:
- You can interact with the timestamp value directly using the {{jsxref("Date/getTime", "getTime()")}} and {{jsxref("Date/setTime", "setTime()")}} methods.
- The {{jsxref("Date/valueOf", "valueOf()")}} and [`[@@toPrimitive]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/@@toPrimitive) (when passed `"number"`) methods — which are automatically called in [number coercion](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number#number_coercion) — return the timestamp, causing `Date` objects to behave like their timestamps when used in number contexts.
- All static methods ({{jsxref("Date.now()")}}, {{jsxref("Date.parse()")}}, and {{jsxref("Date.UTC()")}}) return timestamps instead of `Date` objects.
- The {{jsxref("Date/Date", "Date()")}} constructor can be called with a timestamp as the only argument.
### Date components and time zones
A date is represented internally as a single number, the _timestamp_. When interacting with it, the timestamp needs to be interpreted as a structured date-and-time representation. There are always two ways to interpret a timestamp: as a local time or as a Coordinated Universal Time (UTC), the global standard time defined by the World Time Standard. The local timezone is not stored in the date object, but is determined by the host environment (user's device).
> **Note:** UTC should not be confused with the [Greenwich Mean Time](https://en.wikipedia.org/wiki/Greenwich_Mean_Time) (GMT), because they are not always equal — this is explained in more detail in the linked Wikipedia page.
For example, the timestamp 0 represents a unique instant in history, but it can be interpreted in two ways:
- As a UTC time, it is midnight at the beginning of January 1, 1970, UTC,
- As a local time in New York (UTC-5), it is 19:00:00 on December 31, 1969.
The {{jsxref("Date/getTimezoneOffset", "getTimezoneOffset()")}} method returns the difference between UTC and the local time in minutes. Note that the timezone offset does not only depend on the current timezone, but also on the time represented by the `Date` object, because of daylight saving time and historical changes. In essence, the timezone offset is the offset from UTC time, at the time represented by the `Date` object and at the location of the host environment.
There are two groups of `Date` methods: one group gets and sets various date components by interpreting the timestamp as a local time, while the other uses UTC.
<table class="standard-table">
<thead>
<tr>
<th rowspan="2">Component</th>
<th colspan="2">Local</th>
<th colspan="2">UTC</th>
</tr>
<tr>
<th>Get</th>
<th>Set</th>
<th>Get</th>
<th>Set</th>
</tr>
</thead>
<tbody>
<tr>
<td>Year</td>
<td>{{jsxref("Date/getFullYear", "getFullYear()")}}</td>
<td>{{jsxref("Date/setFullYear", "setFullYear()")}}</td>
<td>{{jsxref("Date/getUTCFullYear", "getUTCFullYear()")}}</td>
<td>{{jsxref("Date/setUTCFullYear", "setUTCFullYear()")}}</td>
</tr>
<tr>
<td>Month</td>
<td>{{jsxref("Date/getMonth", "getMonth()")}}</td>
<td>{{jsxref("Date/setMonth", "setMonth()")}}</td>
<td>{{jsxref("Date/getUTCMonth", "getUTCMonth()")}}</td>
<td>{{jsxref("Date/setUTCMonth", "setUTCMonth()")}}</td>
</tr>
<tr>
<td>Date (of month)</td>
<td>{{jsxref("Date/getDate", "getDate()")}}</td>
<td>{{jsxref("Date/setDate", "setDate()")}}</td>
<td>{{jsxref("Date/getUTCDate", "getUTCDate()")}}</td>
<td>{{jsxref("Date/setUTCDate", "setUTCDate()")}}</td>
</tr>
<tr>
<td>Hours</td>
<td>{{jsxref("Date/getHours", "getHours()")}}</td>
<td>{{jsxref("Date/setHours", "setHours()")}}</td>
<td>{{jsxref("Date/getUTCHours", "getUTCHours()")}}</td>
<td>{{jsxref("Date/setUTCHours", "setUTCHours()")}}</td>
</tr>
<tr>
<td>Minutes</td>
<td>{{jsxref("Date/getMinutes", "getMinutes()")}}</td>
<td>{{jsxref("Date/setMinutes", "setMinutes()")}}</td>
<td>{{jsxref("Date/getUTCMinutes", "getUTCMinutes()")}}</td>
<td>{{jsxref("Date/setUTCMinutes", "setUTCMinutes()")}}</td>
</tr>
<tr>
<td>Seconds</td>
<td>{{jsxref("Date/getSeconds", "getSeconds()")}}</td>
<td>{{jsxref("Date/setSeconds", "setSeconds()")}}</td>
<td>{{jsxref("Date/getUTCSeconds", "getUTCSeconds()")}}</td>
<td>{{jsxref("Date/setUTCSeconds", "setUTCSeconds()")}}</td>
</tr>
<tr>
<td>Milliseconds</td>
<td>{{jsxref("Date/getMilliseconds", "getMilliseconds()")}}</td>
<td>{{jsxref("Date/setMilliseconds", "setMilliseconds()")}}</td>
<td>{{jsxref("Date/getUTCMilliseconds", "getUTCMilliseconds()")}}</td>
<td>{{jsxref("Date/setUTCMilliseconds", "setUTCMilliseconds()")}}</td>
</tr>
<tr>
<td>Day (of week)</td>
<td>{{jsxref("Date/getDay", "getDay()")}}</td>
<td>N/A</td>
<td>{{jsxref("Date/getUTCDay", "getUTCDay()")}}</td>
<td>N/A</td>
</tr>
</tbody>
</table>
The {{jsxref("Date/Date", "Date()")}} constructor can be called with two or more arguments, in which case they are interpreted as the year, month, day, hour, minute, second, and millisecond, respectively, in local time. {{jsxref("Date.UTC()")}} works similarly, but it interprets the components as UTC time and also accepts a single argument representing the year.
> **Note:** Some methods, including the `Date()` constructor, `Date.UTC()`, and the deprecated {{jsxref("Date/getYear", "getYear()")}}/{{jsxref("Date/setYear", "setYear()")}} methods, interpret a two-digit year as a year in the 1900s. For example, `new Date(99, 5, 24)` is interpreted as June 24, 1999, not June 24, 99. See [Interpretation of two-digit years](#interpretation_of_two-digit_years) for more information.
When a segment overflows or underflows its expected range, it usually "carries over to" or "borrows from" the higher segment. For example, if the month is set to 12 (months are zero-based, so December is 11), it become the January of the next year. If the day of month is set to 0, it becomes the last day of the previous month. This also applies to dates specified with the [date time string format](#date_time_string_format).
### Date time string format
There are many ways to format a date as a string. The JavaScript specification only specifies one format to be universally supported: the [_date time string format_](https://tc39.es/ecma262/multipage/numbers-and-dates.html#sec-date-time-string-format), a simplification of the ISO 8601 calendar date extended format. The format is as follows:
```plain
YYYY-MM-DDTHH:mm:ss.sssZ
```
- `YYYY` is the year, with four digits (`0000` to `9999`), or as an _expanded year_ of `+` or `-` followed by six digits. The sign is required for expanded years. `-000000` is explicitly disallowed as a valid year.
- `MM` is the month, with two digits (`01` to `12`). Defaults to `01`.
- `DD` is the day of the month, with two digits (`01` to `31`). Defaults to `01`.
- `T` is a literal character, which indicates the beginning of the _time_ part of the string. The `T` is required when specifying the time part.
- `HH` is the hour, with two digits (`00` to `23`). As a special case, `24:00:00` is allowed, and is interpreted as midnight at the beginning of the next day. Defaults to `00`.
- `mm` is the minute, with two digits (`00` to `59`). Defaults to `00`.
- `ss` is the second, with two digits (`00` to `59`). Defaults to `00`.
- `sss` is the millisecond, with three digits (`000` to `999`). Defaults to `000`.
- `Z` is the timezone offset, which can either be the literal character `Z` (indicating UTC), or `+` or `-` followed by `HH:mm`, the offset in hours and minutes from UTC.
Various components can be omitted, so the following are all valid:
- Date-only form: `YYYY`, `YYYY-MM`, `YYYY-MM-DD`
- Date-time form: one of the above date-only forms, followed by `T`, followed by `HH:mm`, `HH:mm:ss`, or `HH:mm:ss.sss`. Each combination can be followed by a time zone offset.
For example, `"2011-10-10"` (_date-only_ form), `"2011-10-10T14:48:00"` (_date-time_ form), or `"2011-10-10T14:48:00.000+09:00"` (_date-time_ form with milliseconds and time zone) are all valid date time strings.
When the time zone offset is absent, **date-only forms are interpreted as a UTC time and date-time forms are interpreted as local time.** This is due to a historical spec error that was not consistent with ISO 8601 but could not be changed due to web compatibility. See [Broken Parser – A Web Reality Issue](https://maggiepint.com/2017/04/11/fixing-javascript-date-web-compatibility-and-reality/).
{{jsxref("Date.parse()")}} and the {{jsxref("Date/Date", "Date()")}} constructor both accept strings in the date time string format as input. Furthermore, implementations are allowed to support other date formats when the input fails to match this format.
The {{jsxref("Date/toISOString", "toISOString()")}} method returns a string representation of the date in the date time string format, with the time zone offset always set to `Z` (UTC).
> **Note:** You are encouraged to make sure your input conforms to the date time string format above for maximum compatibility, because support for other formats is not guaranteed. However, there are some formats that are supported in all major implementations — like {{rfc(2822)}} format — in which case their usage can be acceptable. Always conduct [cross-browser tests](/en-US/docs/Learn/Tools_and_testing/Cross_browser_testing) to ensure your code works in all target browsers. A library can help if many different formats are to be accommodated.
Non-standard strings can be parsed in any way as desired by the implementation, including the time zone — most implementations use the local time zone by default. Implementations are not required to return invalid date for out-of-bounds date components, although they usually do. A string may have in-bounds date components (with the bounds defined above), but does not represent a date in reality (for example, "February 30"). Implementations behave inconsistently in this case. The [`Date.parse()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse#examples) page offers more examples about these non-standard cases.
### Other ways to format a date
- {{jsxref("Date/toISOString", "toISOString()")}} returns a string in the format `1970-01-01T00:00:00.000Z` (the date time string format introduced above, which is simplified [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601)). {{jsxref("Date/toJSON", "toJSON()")}} calls `toISOString()` and returns the result.
- {{jsxref("Date/toString", "toString()")}} returns a string in the format `Thu Jan 01 1970 00:00:00 GMT+0000 (Coordinated Universal Time)`, while {{jsxref("Date/toDateString", "toDateString()")}} and {{jsxref("Date/toTimeString", "toTimeString()")}} return the date and time parts of the string, respectively. [`[@@toPrimitive]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/@@toPrimitive) (when passed `"string"` or `"default"`) calls `toString()` and returns the result.
- {{jsxref("Date/toUTCString", "toUTCString()")}} returns a string in the format `Thu, 01 Jan 1970 00:00:00 GMT` (generalized {{rfc(7231)}}).
- {{jsxref("Date/toLocaleDateString", "toLocaleDateString()")}}, {{jsxref("Date/toLocaleTimeString", "toLocaleTimeString()")}}, and {{jsxref("Date/toLocaleString", "toLocaleString()")}} use locale-specific date and time formats, usually provided by the [`Intl`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl) API.
See the [Formats of `toString` method return values](#formats_of_tostring_method_return_values) section for examples.
## Constructor
- {{jsxref("Date/Date", "Date()")}}
- : When called as a constructor, returns a new `Date` object. When called as a function, returns a string representation of the current date and time.
## Static methods
- {{jsxref("Date.now()")}}
- : Returns the numeric value corresponding to the current time—the number of milliseconds elapsed since January 1, 1970 00:00:00 UTC, with leap seconds ignored.
- {{jsxref("Date.parse()")}}
- : Parses a string representation of a date and returns the number of milliseconds since 1 January, 1970, 00:00:00 UTC, with leap seconds ignored.
- {{jsxref("Date.UTC()")}}
- : Accepts the same parameters as the longest form of the constructor (i.e. 2 to 7) and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC, with leap seconds ignored.
## Instance properties
These properties are defined on `Date.prototype` and shared by all `Date` instances.
- {{jsxref("Object/constructor", "Date.prototype.constructor")}}
- : The constructor function that created the instance object. For `Date` instances, the initial value is the {{jsxref("Date/Date", "Date")}} constructor.
## Instance methods
- {{jsxref("Date.prototype.getDate()")}}
- : Returns the day of the month (`1` – `31`) for the specified date according to local time.
- {{jsxref("Date.prototype.getDay()")}}
- : Returns the day of the week (`0` – `6`) for the specified date according to local time.
- {{jsxref("Date.prototype.getFullYear()")}}
- : Returns the year (4 digits for 4-digit years) of the specified date according to local time.
- {{jsxref("Date.prototype.getHours()")}}
- : Returns the hour (`0` – `23`) in the specified date according to local time.
- {{jsxref("Date.prototype.getMilliseconds()")}}
- : Returns the milliseconds (`0` – `999`) in the specified date according to local time.
- {{jsxref("Date.prototype.getMinutes()")}}
- : Returns the minutes (`0` – `59`) in the specified date according to local time.
- {{jsxref("Date.prototype.getMonth()")}}
- : Returns the month (`0` – `11`) in the specified date according to local time.
- {{jsxref("Date.prototype.getSeconds()")}}
- : Returns the seconds (`0` – `59`) in the specified date according to local time.
- {{jsxref("Date.prototype.getTime()")}}
- : Returns the numeric value of the specified date as the number of milliseconds since January 1, 1970, 00:00:00 UTC. (Negative values are returned for prior times.)
- {{jsxref("Date.prototype.getTimezoneOffset()")}}
- : Returns the time-zone offset in minutes for the current locale.
- {{jsxref("Date.prototype.getUTCDate()")}}
- : Returns the day (date) of the month (`1` – `31`) in the specified date according to universal time.
- {{jsxref("Date.prototype.getUTCDay()")}}
- : Returns the day of the week (`0` – `6`) in the specified date according to universal time.
- {{jsxref("Date.prototype.getUTCFullYear()")}}
- : Returns the year (4 digits for 4-digit years) in the specified date according to universal time.
- {{jsxref("Date.prototype.getUTCHours()")}}
- : Returns the hours (`0` – `23`) in the specified date according to universal time.
- {{jsxref("Date.prototype.getUTCMilliseconds()")}}
- : Returns the milliseconds (`0` – `999`) in the specified date according to universal time.
- {{jsxref("Date.prototype.getUTCMinutes()")}}
- : Returns the minutes (`0` – `59`) in the specified date according to universal time.
- {{jsxref("Date.prototype.getUTCMonth()")}}
- : Returns the month (`0` – `11`) in the specified date according to universal time.
- {{jsxref("Date.prototype.getUTCSeconds()")}}
- : Returns the seconds (`0` – `59`) in the specified date according to universal time.
- {{jsxref("Date.prototype.getYear()")}} {{deprecated_inline}}
- : Returns the year (usually 2–3 digits) in the specified date according to local time. Use {{jsxref("Date/getFullYear", "getFullYear()")}} instead.
- {{jsxref("Date.prototype.setDate()")}}
- : Sets the day of the month for a specified date according to local time.
- {{jsxref("Date.prototype.setFullYear()")}}
- : Sets the full year (e.g. 4 digits for 4-digit years) for a specified date according to local time.
- {{jsxref("Date.prototype.setHours()")}}
- : Sets the hours for a specified date according to local time.
- {{jsxref("Date.prototype.setMilliseconds()")}}
- : Sets the milliseconds for a specified date according to local time.
- {{jsxref("Date.prototype.setMinutes()")}}
- : Sets the minutes for a specified date according to local time.
- {{jsxref("Date.prototype.setMonth()")}}
- : Sets the month for a specified date according to local time.
- {{jsxref("Date.prototype.setSeconds()")}}
- : Sets the seconds for a specified date according to local time.
- {{jsxref("Date.prototype.setTime()")}}
- : Sets the {{jsxref("Date")}} object to the time represented by a number of milliseconds since January 1, 1970, 00:00:00 UTC. Use negative numbers for times prior.
- {{jsxref("Date.prototype.setUTCDate()")}}
- : Sets the day of the month for a specified date according to universal time.
- {{jsxref("Date.prototype.setUTCFullYear()")}}
- : Sets the full year (e.g. 4 digits for 4-digit years) for a specified date according to universal time.
- {{jsxref("Date.prototype.setUTCHours()")}}
- : Sets the hour for a specified date according to universal time.
- {{jsxref("Date.prototype.setUTCMilliseconds()")}}
- : Sets the milliseconds for a specified date according to universal time.
- {{jsxref("Date.prototype.setUTCMinutes()")}}
- : Sets the minutes for a specified date according to universal time.
- {{jsxref("Date.prototype.setUTCMonth()")}}
- : Sets the month for a specified date according to universal time.
- {{jsxref("Date.prototype.setUTCSeconds()")}}
- : Sets the seconds for a specified date according to universal time.
- {{jsxref("Date.prototype.setYear()")}} {{deprecated_inline}}
- : Sets the year (usually 2–3 digits) for a specified date according to local time. Use {{jsxref("Date/setFullYear", "setFullYear()")}} instead.
- {{jsxref("Date.prototype.toDateString()")}}
- : Returns the "date" portion of the {{jsxref("Date")}} as a human-readable string like `'Thu Apr 12 2018'`.
- {{jsxref("Date.prototype.toISOString()")}}
- : Converts a date to a string following the ISO 8601 Extended Format.
- {{jsxref("Date.prototype.toJSON()")}}
- : Returns a string representing the {{jsxref("Date")}} using {{jsxref("Date/toISOString", "toISOString()")}}. Intended for use by {{jsxref("JSON.stringify()")}}.
- {{jsxref("Date.prototype.toLocaleDateString()")}}
- : Returns a string with a locality sensitive representation of the date portion of this date based on system settings.
- {{jsxref("Date.prototype.toLocaleString()")}}
- : Returns a string with a locality-sensitive representation of this date. Overrides the {{jsxref("Object.prototype.toLocaleString()")}} method.
- {{jsxref("Date.prototype.toLocaleTimeString()")}}
- : Returns a string with a locality-sensitive representation of the time portion of this date, based on system settings.
- {{jsxref("Date.prototype.toString()")}}
- : Returns a string representing the specified {{jsxref("Date")}} object. Overrides the {{jsxref("Object.prototype.toString()")}} method.
- {{jsxref("Date.prototype.toTimeString()")}}
- : Returns the "time" portion of the {{jsxref("Date")}} as a human-readable string.
- {{jsxref("Date.prototype.toUTCString()")}}
- : Converts a date to a string using the UTC timezone.
- {{jsxref("Date.prototype.valueOf()")}}
- : Returns the primitive value of a {{jsxref("Date")}} object. Overrides the {{jsxref("Object.prototype.valueOf()")}} method.
- [`Date.prototype[@@toPrimitive]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/@@toPrimitive)
- : Converts this `Date` object to a primitive value.
## Examples
### Several ways to create a Date object
The following examples show several ways to create JavaScript dates:
> **Note:** Creating a date from a string has a lot of behavior inconsistencies. See [date time string format](#date_time_string_format) for caveats on using different formats.
```js
const today = new Date();
const birthday = new Date("December 17, 1995 03:24:00"); // DISCOURAGED: may not work in all runtimes
const birthday2 = new Date("1995-12-17T03:24:00"); // This is standardized and will work reliably
const birthday3 = new Date(1995, 11, 17); // the month is 0-indexed
const birthday4 = new Date(1995, 11, 17, 3, 24, 0);
const birthday5 = new Date(628021800000); // passing epoch timestamp
```
### Formats of toString method return values
```js
const date = new Date("2020-05-12T23:50:21.817Z");
date.toString(); // Tue May 12 2020 18:50:21 GMT-0500 (Central Daylight Time)
date.toDateString(); // Tue May 12 2020
date.toTimeString(); // 18:50:21 GMT-0500 (Central Daylight Time)
date[Symbol.toPrimitive]("string"); // Tue May 12 2020 18:50:21 GMT-0500 (Central Daylight Time)
date.toISOString(); // 2020-05-12T23:50:21.817Z
date.toJSON(); // 2020-05-12T23:50:21.817Z
date.toUTCString(); // Tue, 12 May 2020 23:50:21 GMT
date.toLocaleString(); // 5/12/2020, 6:50:21 PM
date.toLocaleDateString(); // 5/12/2020
date.toLocaleTimeString(); // 6:50:21 PM
```
### To get Date, Month and Year or Time
```js
const date = new Date("2000-01-17T16:45:30");
const [month, day, year] = [
date.getMonth(),
date.getDate(),
date.getFullYear(),
];
// [0, 17, 2000] as month are 0-indexed
const [hour, minutes, seconds] = [
date.getHours(),
date.getMinutes(),
date.getSeconds(),
];
// [16, 45, 30]
```
### Interpretation of two-digit years
`new Date()` exhibits legacy undesirable, inconsistent behavior with two-digit year values; specifically, when a `new Date()` call is given a two-digit year value, that year value does not get treated as a literal year and used as-is but instead gets interpreted as a relative offset — in some cases as an offset from the year `1900`, but in other cases, as an offset from the year `2000`.
```js
let date = new Date(98, 1); // Sun Feb 01 1998 00:00:00 GMT+0000 (GMT)
date = new Date(22, 1); // Wed Feb 01 1922 00:00:00 GMT+0000 (GMT)
date = new Date("2/1/22"); // Tue Feb 01 2022 00:00:00 GMT+0000 (GMT)
// Legacy method; always interprets two-digit year values as relative to 1900
date.setYear(98);
date.toString(); // Sun Feb 01 1998 00:00:00 GMT+0000 (GMT)
date.setYear(22);
date.toString(); // Wed Feb 01 1922 00:00:00 GMT+0000 (GMT)
```
So, to create and get dates between the years `0` and `99`, instead use the preferred {{jsxref("Date/setFullYear", "setFullYear()")}} and {{jsxref("Date/getFullYear", "getFullYear()")}} methods:.
```js
// Preferred method; never interprets any value as being a relative offset,
// but instead uses the year value as-is
date.setFullYear(98);
date.getFullYear(); // 98 (not 1998)
date.setFullYear(22);
date.getFullYear(); // 22 (not 1922, not 2022)
```
### Calculating elapsed time
The following examples show how to determine the elapsed time between two JavaScript dates in milliseconds.
Due to the differing lengths of days (due to daylight saving changeover), months, and years, expressing elapsed time in units greater than hours, minutes, and seconds requires addressing a number of issues, and should be thoroughly researched before being attempted.
```js
// Using Date objects
const start = Date.now();
// The event to time goes here:
doSomethingForALongTime();
const end = Date.now();
const elapsed = end - start; // elapsed time in milliseconds
```
```js
// Using built-in methods
const start = new Date();
// The event to time goes here:
doSomethingForALongTime();
const end = new Date();
const elapsed = end.getTime() - start.getTime(); // elapsed time in milliseconds
```
```js
// To test a function and get back its return
function printElapsedTime(testFn) {
const startTime = Date.now();
const result = testFn();
const endTime = Date.now();
console.log(`Elapsed time: ${String(endTime - startTime)} milliseconds`);
return result;
}
const yourFunctionReturn = printElapsedTime(yourFunction);
```
> **Note:** In browsers that support the {{domxref("performance_property", "Web Performance API", "", 1)}}'s high-resolution time feature, {{domxref("Performance.now()")}} can provide more reliable and precise measurements of elapsed time than {{jsxref("Date.now()")}}.
### Get the number of seconds since the ECMAScript Epoch
```js
const seconds = Math.floor(Date.now() / 1000);
```
In this case, it's important to return only an integer—so a simple division won't do. It's also important to only return actually elapsed seconds. (That's why this code uses {{jsxref("Math.floor()")}}, and _not_ {{jsxref("Math.round()")}}.)
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Date/Date", "Date()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/date | data/mdn-content/files/en-us/web/javascript/reference/global_objects/date/getutcmilliseconds/index.md | ---
title: Date.prototype.getUTCMilliseconds()
slug: Web/JavaScript/Reference/Global_Objects/Date/getUTCMilliseconds
page-type: javascript-instance-method
browser-compat: javascript.builtins.Date.getUTCMilliseconds
---
{{JSRef}}
The **`getUTCMilliseconds()`** method of {{jsxref("Date")}} instances returns the milliseconds for this date according to universal time.
{{EmbedInteractiveExample("pages/js/date-getutcmilliseconds.html", "shorter")}}
## Syntax
```js-nolint
getUTCMilliseconds()
```
### Parameters
None.
### Return value
An integer, between 0 and 999, representing the milliseconds for the given date according to universal time. Returns `NaN` if the date is [invalid](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#the_epoch_timestamps_and_invalid_date).
Not to be confused with the timestamp. To get the total milliseconds since the epoch, use the [`getTime()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getTime) method.
## Examples
### Using getUTCMilliseconds()
The following example assigns the milliseconds portion of the current time to the variable `milliseconds`.
```js
const today = new Date();
const milliseconds = today.getUTCMilliseconds();
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Date.prototype.getMilliseconds()")}}
- {{jsxref("Date.prototype.setUTCMilliseconds()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/date | data/mdn-content/files/en-us/web/javascript/reference/global_objects/date/tolocaletimestring/index.md | ---
title: Date.prototype.toLocaleTimeString()
slug: Web/JavaScript/Reference/Global_Objects/Date/toLocaleTimeString
page-type: javascript-instance-method
browser-compat: javascript.builtins.Date.toLocaleTimeString
---
{{JSRef}}
The **`toLocaleTimeString()`** method of {{jsxref("Date")}} instances returns a string with a language-sensitive representation of the time portion of this date in the local timezone. In implementations with [`Intl.DateTimeFormat` API](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat) support, this method simply calls `Intl.DateTimeFormat`.
Every time `toLocaleTimeString` is called, it has to perform a search in a big database of localization strings, which is potentially inefficient. When the method is called many times with the same arguments, it is better to create a {{jsxref("Intl.DateTimeFormat")}} object and use its {{jsxref("Intl/DateTimeFormat/format", "format()")}} method, because a `DateTimeFormat` object remembers the arguments passed to it and may decide to cache a slice of the database, so future `format` calls can search for localization strings within a more constrained context.
{{EmbedInteractiveExample("pages/js/date-tolocaletimestring.html")}}
## Syntax
```js-nolint
toLocaleTimeString()
toLocaleTimeString(locales)
toLocaleTimeString(locales, options)
```
### Parameters
The `locales` and `options` parameters customize the behavior of the function and let applications specify the language whose formatting conventions should be used.
In implementations that support the [`Intl.DateTimeFormat` API](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat), these parameters correspond exactly to the [`Intl.DateTimeFormat()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat) constructor's parameters. Implementations without `Intl.DateTimeFormat` support are asked to ignore both parameters, making the locale used and the form of the string returned entirely implementation-dependent.
- `locales` {{optional_inline}}
- : A string with a BCP 47 language tag, or an array of such strings. Corresponds to the [`locales`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat#locales) parameter of the `Intl.DateTimeFormat()` constructor.
In implementations without `Intl.DateTimeFormat` support, this parameter is ignored and the host's locale is usually used.
- `options` {{optional_inline}}
- : An object adjusting the output format. Corresponds to the [`options`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat#options) parameter of the `Intl.DateTimeFormat()` constructor. If `dayPeriod`, `hour`, `minute`, `second`, and `fractionalSecondDigits` are all undefined, then `hour`, `minute`, `second` will be set to `"numeric"`.
In implementations without `Intl.DateTimeFormat` support, this parameter is ignored.
See the [`Intl.DateTimeFormat()` constructor](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat) for details on these parameters and how to use them.
### Return value
A string representing the time portion of the given date according to language-specific conventions.
In implementations with `Intl.DateTimeFormat`, this is equivalent to `new Intl.DateTimeFormat(locales, options).format(date)`, where `options` has been normalized as described above.
> **Note:** Most of the time, the formatting returned by `toLocaleTimeString()` is consistent. However, the output may vary with time, language, and implementation — output variations are by design and allowed by the specification. You should not compare the results of `toLocaleTimeString()` to static values.
## Examples
### Using toLocaleTimeString()
Basic use of this method without specifying a `locale` returns a formatted string in the default locale and with default options.
```js
const date = new Date(Date.UTC(2012, 11, 12, 3, 0, 0));
// toLocaleTimeString() without arguments depends on the implementation,
// the default locale, and the default time zone
console.log(date.toLocaleTimeString());
// "7:00:00 PM" if run in en-US locale with time zone America/Los_Angeles
```
### Checking for support for locales and options parameters
The `locales` and `options` parameters may not be supported in all implementations, because support for the internationalization API is optional, and some systems may not have the necessary data. For implementations without internationalization support, `toLocaleTimeString()` always uses the system's locale, which may not be what you want. Because any implementation that supports the `locales` and `options` parameters must support the {{jsxref("Intl")}} API, you can check the existence of the latter for support:
```js
function toLocaleTimeStringSupportsLocales() {
return (
typeof Intl === "object" &&
!!Intl &&
typeof Intl.DateTimeFormat === "function"
);
}
```
### Using locales
This example shows some of the variations in localized time formats. In order to get the format of the language used in the user interface of your application, make sure to specify that language (and possibly some fallback languages) using the `locales` argument:
```js
const date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));
// formats below assume the local time zone of the locale;
// America/Los_Angeles for the US
// US English uses 12-hour time with AM/PM
console.log(date.toLocaleTimeString("en-US"));
// "7:00:00 PM"
// British English uses 24-hour time without AM/PM
console.log(date.toLocaleTimeString("en-GB"));
// "03:00:00"
// Korean uses 12-hour time with AM/PM
console.log(date.toLocaleTimeString("ko-KR"));
// "오후 12:00:00"
// Arabic in most Arabic speaking countries uses real Arabic digits
console.log(date.toLocaleTimeString("ar-EG"));
// "٧:٠٠:٠٠ م"
// when requesting a language that may not be supported, such as
// Balinese, include a fallback language, in this case Indonesian
console.log(date.toLocaleTimeString(["ban", "id"]));
// "11.00.00"
```
### Using options
The results provided by `toLocaleTimeString()` can be customized using the `options` parameter:
```js
const date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));
// An application may want to use UTC and make that visible
const options = { timeZone: "UTC", timeZoneName: "short" };
console.log(date.toLocaleTimeString("en-US", options));
// "3:00:00 AM GMT"
// Sometimes even the US needs 24-hour time
console.log(date.toLocaleTimeString("en-US", { hour12: false }));
// "19:00:00"
// Show only hours and minutes, use options with the default locale - use an empty array
console.log(
date.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }),
);
// "20:01"
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Intl.DateTimeFormat")}}
- {{jsxref("Date.prototype.toLocaleDateString()")}}
- {{jsxref("Date.prototype.toLocaleString()")}}
- {{jsxref("Date.prototype.toTimeString()")}}
- {{jsxref("Date.prototype.toString()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/date | data/mdn-content/files/en-us/web/javascript/reference/global_objects/date/todatestring/index.md | ---
title: Date.prototype.toDateString()
slug: Web/JavaScript/Reference/Global_Objects/Date/toDateString
page-type: javascript-instance-method
browser-compat: javascript.builtins.Date.toDateString
---
{{JSRef}}
The **`toDateString()`** method of {{jsxref("Date")}} instances returns a string representing the date portion of this date interpreted in the local timezone.
{{EmbedInteractiveExample("pages/js/date-todatestring.html")}}
## Syntax
```js-nolint
toDateString()
```
### Parameters
None.
### Return value
A string representing the date portion of the given date (see description for the format). Returns `"Invalid Date"` if the date is [invalid](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#the_epoch_timestamps_and_invalid_date).
## Description
{{jsxref("Date")}} instances refer to a specific point in time. `toDateString()` interprets the date in the local timezone and formats the _date_ part in English. It always uses the following format, separated by spaces:
1. First three letters of the week day name
2. First three letters of the month name
3. Two-digit day of the month, padded on the left a zero if necessary
4. Four-digit year (at least), padded on the left with zeros if necessary. May have a negative sign
For example: "Thu Jan 01 1970".
- If you only want to get the _time_ part, use {{jsxref("Date/toTimeString", "toTimeString()")}}.
- If you want to get both the date and time, use {{jsxref("Date/toString", "toString()")}}.
- If you want to make the date interpreted as UTC instead of local timezone, use {{jsxref("Date/toUTCString", "toUTCString()")}}.
- If you want to format the date in a more user-friendly format (e.g. localization), use {{jsxref("Date/toLocaleDateString", "toLocaleDateString()")}}.
## Examples
### Using toDateString()
```js
const d = new Date(0);
console.log(d.toString()); // "Thu Jan 01 1970 00:00:00 GMT+0000 (Coordinated Universal Time)"
console.log(d.toDateString()); // "Thu Jan 01 1970"
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Date.prototype.toLocaleDateString()")}}
- {{jsxref("Date.prototype.toTimeString()")}}
- {{jsxref("Date.prototype.toString()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/date | data/mdn-content/files/en-us/web/javascript/reference/global_objects/date/setutcseconds/index.md | ---
title: Date.prototype.setUTCSeconds()
slug: Web/JavaScript/Reference/Global_Objects/Date/setUTCSeconds
page-type: javascript-instance-method
browser-compat: javascript.builtins.Date.setUTCSeconds
---
{{JSRef}}
The **`setUTCSeconds()`** method of {{jsxref("Date")}} instances changes the seconds and/or milliseconds for this date according to universal time.
{{EmbedInteractiveExample("pages/js/date-setutcseconds.html")}}
## Syntax
```js-nolint
setUTCSeconds(secondsValue)
setUTCSeconds(secondsValue, msValue)
```
### Parameters
- `secondsValue`
- : An integer between 0 and 59 representing the seconds.
- `msValue` {{optional_inline}}
- : An integer between 0 and 999 representing the milliseconds.
### Return value
Changes the {{jsxref("Date")}} object in place, and returns its new [timestamp](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#the_epoch_timestamps_and_invalid_date). If a parameter is `NaN` (or other values that get [coerced](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number#number_coercion) to `NaN`, such as `undefined`), the date is set to [Invalid Date](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#the_epoch_timestamps_and_invalid_date) and `NaN` is returned.
## Description
If you do not specify the `msValue` parameter, the value returned from the
{{jsxref("Date/getUTCMilliseconds", "getUTCMilliseconds()")}} method is
used.
If a parameter you specify is outside of the expected range,
`setUTCSeconds()` attempts to update the date information in the
{{jsxref("Date")}} object accordingly. For example, if you use 100 for
`secondsValue`, the minutes stored in the {{jsxref("Date")}} object will be
incremented by 1, and 40 will be used for seconds.
## Examples
### Using setUTCSeconds()
```js
const theBigDay = new Date();
theBigDay.setUTCSeconds(20);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Date.prototype.getUTCSeconds()")}}
- {{jsxref("Date.prototype.setSeconds()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/date | data/mdn-content/files/en-us/web/javascript/reference/global_objects/date/getutcdate/index.md | ---
title: Date.prototype.getUTCDate()
slug: Web/JavaScript/Reference/Global_Objects/Date/getUTCDate
page-type: javascript-instance-method
browser-compat: javascript.builtins.Date.getUTCDate
---
{{JSRef}}
The **`getUTCDate()`** method of {{jsxref("Date")}} instances returns the day of the month for this date according to universal time.
{{EmbedInteractiveExample("pages/js/date-getutcdate.html")}}
## Syntax
```js-nolint
getUTCDate()
```
### Parameters
None.
### Return value
An integer, between 1 and 31, representing day of month for the given date according to universal time. Returns `NaN` if the date is [invalid](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#the_epoch_timestamps_and_invalid_date).
## Examples
### Using getUTCDate()
The following example assigns the day of month of the current date to the variable `dayOfMonth`.
```js
const today = new Date();
const dayOfMonth = today.getUTCDate();
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Date.prototype.getUTCDate()")}}
- {{jsxref("Date.prototype.getDay()")}}
- {{jsxref("Date.prototype.setUTCDate()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/date | data/mdn-content/files/en-us/web/javascript/reference/global_objects/date/tostring/index.md | ---
title: Date.prototype.toString()
slug: Web/JavaScript/Reference/Global_Objects/Date/toString
page-type: javascript-instance-method
browser-compat: javascript.builtins.Date.toString
---
{{JSRef}}
The **`toString()`** method of {{jsxref("Date")}} instances returns a string representing this date interpreted in the local timezone.
{{EmbedInteractiveExample("pages/js/date-tostring.html", "shorter")}}
## Syntax
```js-nolint
toString()
```
### Parameters
None.
### Return value
A string representing the given date (see description for the format). Returns `"Invalid Date"` if the date is [invalid](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#the_epoch_timestamps_and_invalid_date).
## Description
The `toString()` method is part of the [type coercion protocol](/en-US/docs/Web/JavaScript/Data_structures#type_coercion). Because `Date` has a [`[@@toPrimitive]()`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/@@toPrimitive) method, that method always takes priority over `toString()` when a `Date` object is implicitly [coerced to a string](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion). However, `Date.prototype[@@toPrimitive]()` still calls `this.toString()` internally.
The {{jsxref("Date")}} object overrides the {{jsxref("Object/toString", "toString()")}} method of {{jsxref("Object")}}. `Date.prototype.toString()` returns a string representation of the Date as interpreted in the local timezone, containing both the date and the time — it joins the string representation specified in {{jsxref("Date/toDateString", "toDateString()")}} and {{jsxref("Date/toTimeString", "toTimeString()")}} together, adding a space in between. For example: "Thu Jan 01 1970 00:00:00 GMT+0000 (Coordinated Universal Time)".
`Date.prototype.toString()` must be called on {{jsxref("Date")}} instances. If the `this` value does not inherit from `Date.prototype`, a {{jsxref("TypeError")}} is thrown.
- If you only want to get the _date_ part, use {{jsxref("Date/toDateString", "toDateString()")}}.
- If you only want to get the _time_ part, use {{jsxref("Date/toTimeString", "toTimeString()")}}.
- If you want to make the date interpreted as UTC instead of local timezone, use {{jsxref("Date/toUTCString", "toUTCString()")}}.
- If you want to format the date in a more user-friendly format (e.g. localization), use {{jsxref("Date/toLocaleString", "toLocaleString()")}}.
## Examples
### Using toString()
```js
const d = new Date(0);
console.log(d.toString()); // "Thu Jan 01 1970 00:00:00 GMT+0000 (Coordinated Universal Time)"
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Object.prototype.toString()")}}
- {{jsxref("Date.prototype.toDateString()")}}
- {{jsxref("Date.prototype.toLocaleString()")}}
- {{jsxref("Date.prototype.toTimeString()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/date | data/mdn-content/files/en-us/web/javascript/reference/global_objects/date/getseconds/index.md | ---
title: Date.prototype.getSeconds()
slug: Web/JavaScript/Reference/Global_Objects/Date/getSeconds
page-type: javascript-instance-method
browser-compat: javascript.builtins.Date.getSeconds
---
{{JSRef}}
The **`getSeconds()`** method of {{jsxref("Date")}} instances returns the seconds for this date according to local time.
{{EmbedInteractiveExample("pages/js/date-getseconds.html", "shorter")}}
## Syntax
```js-nolint
getSeconds()
```
### Parameters
None.
### Return value
An integer, between 0 and 59, representing the seconds for the given date according to local time. Returns `NaN` if the date is [invalid](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#the_epoch_timestamps_and_invalid_date).
## Examples
### Using getSeconds()
The `seconds` variable has value `30`, based on the value of the {{jsxref("Date")}} object `xmas95`.
```js
const xmas95 = new Date("1995-12-25T23:15:30");
const seconds = xmas95.getSeconds();
console.log(seconds); // 30
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Date.prototype.getUTCSeconds()")}}
- {{jsxref("Date.prototype.setSeconds()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/date | data/mdn-content/files/en-us/web/javascript/reference/global_objects/date/setmonth/index.md | ---
title: Date.prototype.setMonth()
slug: Web/JavaScript/Reference/Global_Objects/Date/setMonth
page-type: javascript-instance-method
browser-compat: javascript.builtins.Date.setMonth
---
{{JSRef}}
The **`setMonth()`** method of {{jsxref("Date")}} instances changes the month and/or day of the month for this date according to local time.
{{EmbedInteractiveExample("pages/js/date-setmonth.html")}}
## Syntax
```js-nolint
setMonth(monthValue)
setMonth(monthValue, dateValue)
```
### Parameters
- `monthValue`
- : An integer representing the month: 0 for January, 1 for February, and so on.
- `dateValue` {{optional_inline}}
- : An integer from 1 to 31 representing the day of the month.
### Return value
Changes the {{jsxref("Date")}} object in place, and returns its new [timestamp](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#the_epoch_timestamps_and_invalid_date). If a parameter is `NaN` (or other values that get [coerced](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number#number_coercion) to `NaN`, such as `undefined`), the date is set to [Invalid Date](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#the_epoch_timestamps_and_invalid_date) and `NaN` is returned.
## Description
If you do not specify the `dateValue` parameter, the same value as what is returned by {{jsxref("Date/getDate", "getDate()")}} is used.
If a parameter you specify is outside of the expected range, other parameters and the date information in the {{jsxref("Date")}} object are updated accordingly. For example, if you specify 15 for `monthValue`, the year is incremented by 1, and 3 is used for month.
The current day of month will have an impact on the behavior of this method.
Conceptually it will add the number of days given by the current day of the month to the
1st day of the new month specified as the parameter, to return the new date.
For example, if the current value is 31st January 2016, calling setMonth with a value of 1 will return 2nd March 2016.
This is because in 2016 February had 29 days.
## Examples
### Using setMonth()
```js
const theBigDay = new Date();
theBigDay.setMonth(6);
//Watch out for end of month transitions
const endOfMonth = new Date(2016, 7, 31);
endOfMonth.setMonth(1);
console.log(endOfMonth); //Wed Mar 02 2016 00:00:00
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Date.prototype.getMonth()")}}
- {{jsxref("Date.prototype.setUTCMonth()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/date | data/mdn-content/files/en-us/web/javascript/reference/global_objects/date/parse/index.md | ---
title: Date.parse()
slug: Web/JavaScript/Reference/Global_Objects/Date/parse
page-type: javascript-static-method
browser-compat: javascript.builtins.Date.parse
---
{{JSRef}}
The **`Date.parse()`** static method parses a string representation of a date, and returns the date's [timestamp](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#the_epoch_timestamps_and_invalid_date).
Only the [date time string format](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#date_time_string_format) is explicitly specified to be supported. Other formats are implementation-defined and may not work across all browsers. A library can help if many different formats are to be accommodated.
{{EmbedInteractiveExample("pages/js/date-parse.html")}}
## Syntax
```js-nolint
Date.parse(dateString)
```
### Parameters
- `dateString`
- : A string in [the date time string format](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#date_time_string_format). See the linked reference for caveats on using different formats.
### Return value
A number representing the [timestamp](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#the_epoch_timestamps_and_invalid_date) of the given date. If `dateString` fails to be parsed as a valid date, {{jsxref("NaN")}} is returned.
## Description
This function is useful for setting date values based on string values, for example in conjunction with the {{jsxref("Date/setTime", "setTime()")}} method.
Because `parse()` is a static method of `Date`, you always use it as `Date.parse()`, rather than as a method of a `Date` object you created.
## Examples
### Using Date.parse()
The following calls all return `1546300800000`. The first will imply UTC time because it's date-only, and the others explicitly specify the UTC timezone.
```js
Date.parse("2019-01-01");
Date.parse("2019-01-01T00:00:00.000Z");
Date.parse("2019-01-01T00:00:00.000+00:00");
```
The following call, which does not specify a time zone will be set to 2019-01-01 at 00:00:00 in the local timezone of the system, because it has both date and time.
```js
Date.parse("2019-01-01T00:00:00");
```
### Non-standard date strings
> **Note:** This section contains implementation-specific behavior that can be inconsistent across implementations.
Implementations usually default to the local time zone when the date string is non-standard. For consistency, we will assume that the code uses the UTC timezone.
> **Note:** The local time zone offset comes from the system setting of the device and is then applied to the date being parsed. [Daylight Saving Time (DST), of the local time zone, can also have an effect on this too](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getTimezoneOffset#varied_results_in_daylight_saving_time_dst_regions).
```js
Date.parse("Jan 1, 1970"); // 0 in all implementations
Date.parse("Thu, 01 Jan 1970 00:00:00"); // 0 in all implementations
Date.parse("1970,1,1"); // 0 in Chrome and Firefox, NaN in Safari
Date.parse("02 01 1970");
// 2678400000 in Chrome and Firefox (Sun Feb 01 1970 00:00:00 GMT+0000);
// NaN in Safari
// With explicit timezone
Date.parse("Thu, 01 Jan 1970 00:00:00 GMT+0300");
// -10800000 in all implementations in all timezones
// Single number
Date.parse("0");
// NaN in Firefox ≤122
// 946684800000 in Chrome and Firefox ≥123 (Sat Jan 01 2000 00:00:00 GMT+0000);
// -62167219200000 in Safari (Sat Jan 01 0000 00:00:00 GMT+0000)
// Two-digit number that may be a month
Date.parse("28");
// NaN Chrome and Firefox
// -61283606400000 in Safari (Fri Dec 31 0027 23:58:45 GMT-0001)
// Two-digit year
Date.parse("70/01/01"); // 0 in all implementations
// Out-of-bounds date components
Date.parse("2014-25-23"); // NaN in all implementations
Date.parse("Mar 32, 2014"); // NaN in all implementations
Date.parse("2014/25/23"); // NaN in all implementations
Date.parse("2014-02-30");
// NaN in Safari
// 1393718400000 in Chrome and Firefox (Sun Mar 02 2014 00:00:00 GMT+0000)
Date.parse("02/30/2014"); // 1393718400000 in all implementations
// Chrome, Safari, and Firefox 122 and later parse only the first three letters for the month.
// FF121 and earlier parse first three letters and any substring up to the correct month name.
Date.parse("04 Dec 1995"); // 818031600000 in all implementations
Date.parse("04 Decem 1995"); // 818031600000 in all implementations
Date.parse("04 December 1995"); // 818031600000 in all implementations
Date.parse("04 DecFoo 1995"); // NaN in Firefox 121 and earlier. 818031600000 in other implementations
Date.parse("04 De 1995"); // NaN in all implementations
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Date.UTC()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/date | data/mdn-content/files/en-us/web/javascript/reference/global_objects/date/setutcdate/index.md | ---
title: Date.prototype.setUTCDate()
slug: Web/JavaScript/Reference/Global_Objects/Date/setUTCDate
page-type: javascript-instance-method
browser-compat: javascript.builtins.Date.setUTCDate
---
{{JSRef}}
The **`setUTCDate()`** method of {{jsxref("Date")}} instances changes the day of the month for this date according to universal time.
{{EmbedInteractiveExample("pages/js/date-setutcdate.html")}}
## Syntax
```js-nolint
setUTCDate(dateValue)
```
### Parameters
- `dateValue`
- : An integer from 1 to 31 representing the day of the month.
### Return value
Changes the {{jsxref("Date")}} object in place, and returns its new [timestamp](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#the_epoch_timestamps_and_invalid_date). If `dateValue` is `NaN` (or other values that get [coerced](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number#number_coercion) to `NaN`, such as `undefined`), the date is set to [Invalid Date](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#the_epoch_timestamps_and_invalid_date) and `NaN` is returned.
## Description
If the `dateValue` is outside of the range of date values for the month, `setDate()` will update the {{jsxref("Date")}} object accordingly.
For example, if 0 is provided for `dateValue`, the date will be set to the last day of the previous month. If you use 40 for `dateValue`, and the month stored in the {{jsxref("Date")}} object is June, the day will be changed to 10 and the month will be incremented to July.
If a negative number is provided for `dateValue`, the date will be set counting backwards from the last day of the previous month. -1 would result in the date being set to 1 day before the last day of the previous month.
## Examples
### Using setUTCDate()
```js
const theBigDay = new Date();
theBigDay.setUTCDate(20);
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Date.prototype.getUTCDate()")}}
- {{jsxref("Date.prototype.setDate()")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/date | data/mdn-content/files/en-us/web/javascript/reference/global_objects/date/@@toprimitive/index.md | ---
title: Date.prototype[@@toPrimitive]()
slug: Web/JavaScript/Reference/Global_Objects/Date/@@toPrimitive
page-type: javascript-instance-method
browser-compat: javascript.builtins.Date.@@toPrimitive
---
{{JSRef}}
The **`[@@toPrimitive]()`** method of {{jsxref("Date")}} instances returns a primitive value representing this date. It may either be a string or a number, depending on the hint given.
{{EmbedInteractiveExample("pages/js/date-toprimitive.html")}}
## Syntax
```js-nolint
date[Symbol.toPrimitive](hint)
```
### Parameters
- `hint`
- : A string representing the type of the primitive value to return. The following values are valid:
- `"string"` or `"default"`: The method should return a string.
- `"number"`: The method should return a number.
### Return value
If `hint` is `"string"` or `"default"`, this method returns a string by [coercing the `this` value to a string](/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#string_coercion) (first trying `toString()` then trying `valueOf()`).
If `hint` is `"number"`, this method returns a number by [coercing the `this` value to a number](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number#number_coercion) (first trying `valueOf()` then trying `toString()`).
### Exceptions
- {{jsxref("TypeError")}}
- : Thrown if the `hint` argument is not one of the three valid values.
## Description
The `[@@toPrimitive]()` method is part of the [type coercion protocol](/en-US/docs/Web/JavaScript/Data_structures#type_coercion). JavaScript always calls the `[@@toPrimitive]()` method in priority to convert an object to a primitive value. You rarely need to invoke the `[@@toPrimitive]()` method yourself; JavaScript automatically invokes it when encountering an object where a primitive value is expected.
The `[@@toPrimitive]()` method of the {{jsxref("Date")}} object returns a primitive value by either invoking {{jsxref("Date/valueOf", "this.valueOf()")}} and returning a number, or invoking {{jsxref("Date/toString", "this.toString()")}} and returning a string. It exists to override the default [primitive coercion](/en-US/docs/Web/JavaScript/Data_structures#primitive_coercion) process to return a string instead of a number, because primitive coercion, by default, calls {{jsxref("Date/valueOf", "valueOf()")}} before {{jsxref("Date/toString", "toString()")}}. With the custom `[@@toPrimitive]()`, `new Date(0) + 1` returns `"Thu Jan 01 1970 00:00:00 GMT+0000 (Coordinated Universal Time)1"` (a string) instead of `1` (a number).
## Examples
### Using \[@@toPrimitive]()
```js
const d = new Date(0); // 1970-01-01T00:00:00.000Z
d[Symbol.toPrimitive]("string"); // "Thu Jan 01 1970 00:00:00 GMT+0000 (Coordinated Universal Time)"
d[Symbol.toPrimitive]("number"); // 0
d[Symbol.toPrimitive]("default"); // "Thu Jan 01 1970 00:00:00 GMT+0000 (Coordinated Universal Time)"
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Symbol.toPrimitive")}}
| 0 |
data/mdn-content/files/en-us/web/javascript/reference/global_objects/date | data/mdn-content/files/en-us/web/javascript/reference/global_objects/date/getdate/index.md | ---
title: Date.prototype.getDate()
slug: Web/JavaScript/Reference/Global_Objects/Date/getDate
page-type: javascript-instance-method
browser-compat: javascript.builtins.Date.getDate
---
{{JSRef}}
The **`getDate()`** method of {{jsxref("Date")}} instances returns the day of the month for this date according to local time.
{{EmbedInteractiveExample("pages/js/date-getdate.html", "shorter")}}
## Syntax
```js-nolint
getDate()
```
### Parameters
None.
### Return value
An integer, between 1 and 31, representing the day of the month for the given date according to local time. Returns `NaN` if the date is [invalid](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#the_epoch_timestamps_and_invalid_date).
## Examples
### Using getDate()
The `day` variable has value `25`, based on the value of the {{jsxref("Date")}} object `xmas95`.
```js
const xmas95 = new Date("1995-12-25T23:15:30");
const day = xmas95.getDate();
console.log(day); // 25
```
## Specifications
{{Specifications}}
## Browser compatibility
{{Compat}}
## See also
- {{jsxref("Date.prototype.getUTCDate()")}}
- {{jsxref("Date.prototype.getUTCDay()")}}
- {{jsxref("Date.prototype.setDate()")}}
| 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.