diff --git a/files/en-us/_redirects.txt b/files/en-us/_redirects.txt index 425e28f4a45dd41..61c25aad4b1ccdb 100644 --- a/files/en-us/_redirects.txt +++ b/files/en-us/_redirects.txt @@ -12791,6 +12791,7 @@ /en-US/docs/Web/JavaScript/Guide/Inheritance_Revisited /en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain /en-US/docs/Web/JavaScript/Guide/Inheritance_and_the_prototype_chain /en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain /en-US/docs/Web/JavaScript/Guide/JavaScript_Overview /en-US/docs/Web/JavaScript/Guide/Introduction +/en-US/docs/Web/JavaScript/Guide/Numbers_and_dates /en-US/docs/Web/JavaScript/Guide/Numbers_and_strings /en-US/docs/Web/JavaScript/Guide/Obsolete_Pages /en-US/docs/Web/JavaScript/Guide /en-US/docs/Web/JavaScript/Guide/Obsolete_Pages/Block_Statement /en-US/docs/Web/JavaScript/Guide/Control_flow_and_error_handling /en-US/docs/Web/JavaScript/Guide/Obsolete_Pages/Calling_Functions /en-US/docs/Web/JavaScript/Guide/Functions @@ -12876,6 +12877,7 @@ /en-US/docs/Web/JavaScript/Guide/Regular_expressions/Unicode_property_escapes /en-US/docs/Web/JavaScript/Reference/Regular_expressions/Unicode_character_class_escape /en-US/docs/Web/JavaScript/Guide/Sameness /en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness /en-US/docs/Web/JavaScript/Guide/Statements /en-US/docs/Web/JavaScript/Guide/Control_flow_and_error_handling +/en-US/docs/Web/JavaScript/Guide/Text_formatting /en-US/docs/Web/JavaScript/Guide/Numbers_and_strings /en-US/docs/Web/JavaScript/Guide/The_Iterator_protocol /en-US/docs/Web/JavaScript/Reference/Iteration_protocols /en-US/docs/Web/JavaScript/Guide/The_legacy_Iterator_protocol /en-US/docs/Web/JavaScript/Reference/Deprecated_and_obsolete_features /en-US/docs/Web/JavaScript/Guide/Using_native_JSON /en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON diff --git a/files/en-us/_wikihistory.json b/files/en-us/_wikihistory.json index 0c0776ae71796e0..906cb4966f99e1d 100644 --- a/files/en-us/_wikihistory.json +++ b/files/en-us/_wikihistory.json @@ -102176,7 +102176,7 @@ "douglasnaphas" ] }, - "Web/JavaScript/Guide/Numbers_and_dates": { + "Web/JavaScript/Guide/Numbers_and_strings": { "modified": "2020-11-14T07:27:01.088Z", "contributors": [ "mfuji09", @@ -102422,31 +102422,6 @@ "jpmedley" ] }, - "Web/JavaScript/Guide/Text_formatting": { - "modified": "2020-05-25T10:48:56.137Z", - "contributors": [ - "fscholz", - "wbamberg", - "bma", - "alattalatta", - "vriojtg", - "sbfraser01", - "chrisdavidmills", - "JigneshMistry", - "stephaniehobson", - "SphinxKnight", - "amir77ameri", - "ThomasEugeneBishop", - "nmve", - "kdex", - "Jeremie", - "danielinux7", - "gportioli", - "xfq", - "mahzaib", - "kscarfone" - ] - }, "Web/JavaScript/Guide/Typed_arrays": { "modified": "2020-10-15T21:04:01.905Z", "contributors": [ diff --git a/files/en-us/learn_web_development/core/scripting/math/index.md b/files/en-us/learn_web_development/core/scripting/math/index.md index a819a8b331c0b1f..816315c3ae72519 100644 --- a/files/en-us/learn_web_development/core/scripting/math/index.md +++ b/files/en-us/learn_web_development/core/scripting/math/index.md @@ -456,7 +456,7 @@ In the next article, we'll explore text and how JavaScript allows us to manipula ## See also -- [Numbers and dates](/en-US/docs/Web/JavaScript/Guide/Numbers_and_dates) +- [Numbers and strings](/en-US/docs/Web/JavaScript/Guide/Numbers_and_strings) - [Expressions and operators](/en-US/docs/Web/JavaScript/Guide/Expressions_and_operators) {{PreviousMenuNext("Learn_web_development/Core/Scripting/Variables", "Learn_web_development/Core/Scripting/Strings", "Learn_web_development/Core/Scripting")}} diff --git a/files/en-us/web/html/date_and_time_formats/index.md b/files/en-us/web/html/date_and_time_formats/index.md index 37b11741315b27b..bd5e6ba08279a11 100644 --- a/files/en-us/web/html/date_and_time_formats/index.md +++ b/files/en-us/web/html/date_and_time_formats/index.md @@ -430,6 +430,6 @@ Why worry about the Y10K problem if it is going to happen many centuries after y - {{HTMLElement("input")}} - {{HTMLElement("ins")}} and {{HTMLElement("del")}}: see the `datetime` attribute, which specifies either a date or a local date and time at which the content was inserted or deleted - [The ISO 8601 specification](https://www.iso.org/iso-8601-date-and-time-format.html) -- [Numbers and Dates](/en-US/docs/Web/JavaScript/Guide/Numbers_and_dates) in the [JavaScript Guide](/en-US/docs/Web/JavaScript/Guide) +- [Representing dates & times](/en-US/docs/Web/JavaScript/Guide/Representing_dates_times) in the [JavaScript Guide](/en-US/docs/Web/JavaScript/Guide) - The JavaScript {{jsxref("Date")}} object - The [`Intl.DateTimeFormat`](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat) object for formatting dates and times for a given locale diff --git a/files/en-us/web/javascript/guide/expressions_and_operators/index.md b/files/en-us/web/javascript/guide/expressions_and_operators/index.md index d30eaf61df658da..79c98be3db2753f 100644 --- a/files/en-us/web/javascript/guide/expressions_and_operators/index.md +++ b/files/en-us/web/javascript/guide/expressions_and_operators/index.md @@ -4,7 +4,7 @@ slug: Web/JavaScript/Guide/Expressions_and_operators page-type: guide --- -{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Functions", "Web/JavaScript/Guide/Numbers_and_dates")}} +{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Functions", "Web/JavaScript/Guide/Numbers_and_strings")}} This chapter describes JavaScript's expressions and operators, including assignment, comparison, arithmetic, bitwise, logical, string, ternary and more. @@ -1148,4 +1148,4 @@ super(args); // calls the parent constructor. super.functionOnParent(args); ``` -{{PreviousNext("Web/JavaScript/Guide/Functions", "Web/JavaScript/Guide/Numbers_and_dates")}} +{{PreviousNext("Web/JavaScript/Guide/Functions", "Web/JavaScript/Guide/Numbers_and_strings")}} diff --git a/files/en-us/web/javascript/guide/index.md b/files/en-us/web/javascript/guide/index.md index 519ddda2756fb4f..42bb63e60f2f8f8 100644 --- a/files/en-us/web/javascript/guide/index.md +++ b/files/en-us/web/javascript/guide/index.md @@ -73,24 +73,33 @@ Overview: [Expressions and operators](/en-US/docs/Web/JavaScript/Guide/Expressio - [Bitwise](/en-US/docs/Web/JavaScript/Guide/Expressions_and_operators#bitwise_operators) & [logical operators](/en-US/docs/Web/JavaScript/Guide/Expressions_and_operators#logical_operators) - [Conditional (ternary) operator]() -## Numbers and dates +## Numbers and strings -Overview: [Numbers and dates](/en-US/docs/Web/JavaScript/Guide/Numbers_and_dates) +Overview: [Numbers and strings](/en-US/docs/Web/JavaScript/Guide/Numbers_and_strings) -- [Number literals](/en-US/docs/Web/JavaScript/Guide/Numbers_and_dates#numbers) -- [`Number` object](/en-US/docs/Web/JavaScript/Guide/Numbers_and_dates#number_object) -- [`Math` object](/en-US/docs/Web/JavaScript/Guide/Numbers_and_dates#math_object) -- [`Date` object](/en-US/docs/Web/JavaScript/Guide/Numbers_and_dates#date_object) +- [Numbers](/en-US/docs/Web/JavaScript/Guide/Numbers_and_strings#numbers) +- [`Number` object](/en-US/docs/Web/JavaScript/Guide/Numbers_and_strings#number_object) +- [`Math` object](/en-US/docs/Web/JavaScript/Guide/Numbers_and_strings#math_object) +- [Strings](/en-US/docs/Web/JavaScript/Guide/Numbers_and_strings#strings) +- [`String` object](/en-US/docs/Web/JavaScript/Guide/Numbers_and_strings#string_object) +- [Template literals](/en-US/docs/Web/JavaScript/Guide/Numbers_and_strings#template_literals) -## Text formatting +## Representing dates & times -Overview: [Text formatting](/en-US/docs/Web/JavaScript/Guide/Text_formatting) +Overview: [Representing dates & times](/en-US/docs/Web/JavaScript/Guide/Representing_dates_times) -- [String literals](/en-US/docs/Web/JavaScript/Guide/Text_formatting#string_literals) -- [`String` object](/en-US/docs/Web/JavaScript/Guide/Text_formatting#string_objects) -- [Template literals](/en-US/docs/Web/JavaScript/Guide/Text_formatting#multi-line_template_literals) -- [Internationalization](/en-US/docs/Web/JavaScript/Guide/Text_formatting#internationalization) -- [Regular Expressions](/en-US/docs/Web/JavaScript/Guide/Regular_expressions) +- [`Date` object](/en-US/docs/Web/JavaScript/Guide/Representing_dates_times#date_object) + +## Regular expressions + +Overview: [Regular expressions](/en-US/docs/Web/JavaScript/Guide/Regular_expressions) + +- [Creating a regular expression](/en-US/docs/Web/JavaScript/Guide/Regular_expressions#creating_a_regular_expression) +- [Writing a regular expression pattern](/en-US/docs/Web/JavaScript/Guide/Regular_expressions#writing_a_regular_expression_pattern) + - [Assertions](/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Assertions) + - [Character classes](/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Character_classes) + - [Groups and backreferences](/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Groups_and_backreferences) + - [Quantifiers](/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Quantifiers) ## Indexed collections @@ -145,6 +154,14 @@ Overview: [Iterators and generators](/en-US/docs/Web/JavaScript/Guide/Iterators_ - [Iterables](/en-US/docs/Web/JavaScript/Guide/Iterators_and_generators#iterables) - [Generators](/en-US/docs/Web/JavaScript/Guide/Iterators_and_generators#generator_functions) +## Internationalization + +Overview: [Internationalization](/en-US/docs/Web/JavaScript/Guide/Internationalization) + +- [Date and time formatting](/en-US/docs/Web/JavaScript/Guide/Internationalization#date_and_time_formatting) +- [Number formatting](/en-US/docs/Web/JavaScript/Guide/Internationalization#number_formatting) +- [Collation](/en-US/docs/Web/JavaScript/Guide/Internationalization#collation) + ## Meta programming Overview: [Meta programming](/en-US/docs/Web/JavaScript/Guide/Meta_programming) diff --git a/files/en-us/web/javascript/guide/internationalization/index.md b/files/en-us/web/javascript/guide/internationalization/index.md new file mode 100644 index 000000000000000..ebf923b3902742f --- /dev/null +++ b/files/en-us/web/javascript/guide/internationalization/index.md @@ -0,0 +1,84 @@ +--- +title: Internationalization +slug: Web/JavaScript/Guide/Internationalization +page-type: guide +--- + +{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Iterators_and_generators", "Web/JavaScript/Guide/Meta_programming")}} + +The {{jsxref("Intl")}} object is the namespace for the ECMAScript Internationalization API, which provides a wide range of locale- and culture-sensitive data and operations. + +## Date and time formatting + +The {{jsxref("Intl.DateTimeFormat")}} object is useful for formatting date and time. The following formats a date for English as used in the United States. (The result is different in another time zone.) + +```js +// July 17, 2014 00:00:00 UTC: +const july172014 = new Date("2014-07-17"); + +const options = { + year: "2-digit", + month: "2-digit", + day: "2-digit", + hour: "2-digit", + minute: "2-digit", + timeZoneName: "short", +}; +const americanDateTime = new Intl.DateTimeFormat("en-US", options).format; + +// Local timezone vary depending on your settings +// In CEST, logs: 07/17/14, 02:00 AM GMT+2 +// In PDT, logs: 07/16/14, 05:00 PM GMT-7 +console.log(americanDateTime(july172014)); +``` + +## Number formatting + +The {{jsxref("Intl.NumberFormat")}} object is useful for formatting numbers, for example currencies. + +```js +const gasPrice = new Intl.NumberFormat("en-US", { + style: "currency", + currency: "USD", + minimumFractionDigits: 3, +}); + +console.log(gasPrice.format(5.259)); // $5.259 + +const hanDecimalRMBInChina = new Intl.NumberFormat("zh-CN-u-nu-hanidec", { + style: "currency", + currency: "CNY", +}); + +console.log(hanDecimalRMBInChina.format(1314.25)); // ¥ 一,三一四.二五 +``` + +## Collation + +The {{jsxref("Intl.Collator")}} object is useful for comparing and sorting strings. + +For example, there are actually two different sort orders in German, _phonebook_ and _dictionary_. Phonebook sort emphasizes sound, and it's as if "ä", "ö", and so on were expanded to "ae", "oe", and so on prior to sorting. + +```js +const names = ["Hochberg", "Hönigswald", "Holzman"]; + +const germanPhonebook = new Intl.Collator("de-DE-u-co-phonebk"); + +// as if sorting ["Hochberg", "Hoenigswald", "Holzman"]: +console.log(names.sort(germanPhonebook.compare).join(", ")); +// "Hochberg, Hönigswald, Holzman" +``` + +Some German words conjugate with extra umlauts, so in dictionaries it's sensible to order ignoring umlauts (except when ordering words differing _only_ by umlauts: _schon_ before _schön_). + +```js +const germanDictionary = new Intl.Collator("de-DE-u-co-dict"); + +// as if sorting ["Hochberg", "Honigswald", "Holzman"]: +console.log(names.sort(germanDictionary.compare).join(", ")); +// "Hochberg, Holzman, Hönigswald" +``` + +For more information about the {{jsxref("Intl")}} API, see also [Introducing the JavaScript Internationalization API](https://hacks.mozilla.org/2014/12/introducing-the-javascript-internationalization-api/). + +{{PreviousNext("Web/JavaScript/Guide/Iterators_and_generators", "Web/JavaScript/Guide/Meta_programming")}} diff --git a/files/en-us/web/javascript/guide/iterators_and_generators/index.md b/files/en-us/web/javascript/guide/iterators_and_generators/index.md index 8753c53ab4755e2..cff573845cd0145 100644 --- a/files/en-us/web/javascript/guide/iterators_and_generators/index.md +++ b/files/en-us/web/javascript/guide/iterators_and_generators/index.md @@ -4,7 +4,7 @@ slug: Web/JavaScript/Guide/Iterators_and_generators page-type: guide --- -{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Typed_arrays", "Web/JavaScript/Guide/Meta_programming")}} +{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Typed_arrays", "Web/JavaScript/Guide/Internationalization")}} Iterators and Generators bring the concept of iteration directly into the core language and provide a mechanism for customizing the behavior of {{jsxref("Statements/for...of", "for...of")}} loops. @@ -234,4 +234,4 @@ If the exception is not caught from within the generator, it will propagate up t Generators have a {{jsxref("Generator/return", "return()")}} method that returns the given value and finishes the generator itself. -{{PreviousNext("Web/JavaScript/Guide/Typed_arrays", "Web/JavaScript/Guide/Meta_programming")}} +{{PreviousNext("Web/JavaScript/Guide/Typed_arrays", "Web/JavaScript/Guide/Internationalization")}} diff --git a/files/en-us/web/javascript/guide/meta_programming/index.md b/files/en-us/web/javascript/guide/meta_programming/index.md index 57e311e4a0851cf..3ded1b7f589eec1 100644 --- a/files/en-us/web/javascript/guide/meta_programming/index.md +++ b/files/en-us/web/javascript/guide/meta_programming/index.md @@ -4,7 +4,7 @@ slug: Web/JavaScript/Guide/Meta_programming page-type: guide --- -{{jsSidebar("JavaScript Guide")}}{{PreviousNext("Web/JavaScript/Guide/Iterators_and_generators", "Web/JavaScript/Guide/Modules")}} +{{jsSidebar("JavaScript Guide")}}{{PreviousNext("Web/JavaScript/Guide/Internationalization", "Web/JavaScript/Guide/Modules")}} The {{jsxref("Proxy")}} and {{jsxref("Reflect")}} objects allow you to intercept and define custom behavior for fundamental language operations (e.g. property lookup, assignment, enumeration, function invocation, etc.). With the help of these two objects you are able to program at the meta level of JavaScript. @@ -282,4 +282,4 @@ if (Reflect.defineProperty(target, property, attributes)) { } ``` -{{PreviousNext("Web/JavaScript/Guide/Iterators_and_generators", "Web/JavaScript/Guide/Modules")}} +{{PreviousNext("Web/JavaScript/Guide/Internationalization", "Web/JavaScript/Guide/Modules")}} diff --git a/files/en-us/web/javascript/guide/numbers_and_dates/index.md b/files/en-us/web/javascript/guide/numbers_and_strings/index.md similarity index 70% rename from files/en-us/web/javascript/guide/numbers_and_dates/index.md rename to files/en-us/web/javascript/guide/numbers_and_strings/index.md index f3e63d33f23f483..76610a371a8c42f 100644 --- a/files/en-us/web/javascript/guide/numbers_and_dates/index.md +++ b/files/en-us/web/javascript/guide/numbers_and_strings/index.md @@ -1,12 +1,12 @@ --- title: Numbers and dates -slug: Web/JavaScript/Guide/Numbers_and_dates +slug: Web/JavaScript/Guide/Numbers_and_strings page-type: guide --- -{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Expressions_and_operators", "Web/JavaScript/Guide/Text_formatting")}} +{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Expressions_and_operators", "Web/JavaScript/Guide/Representing_dates_times")}} -This chapter introduces the concepts, objects and functions used to work with and perform calculations using numbers and dates in JavaScript. This includes using numbers written in various bases including decimal, binary, and hexadecimal, as well as the use of the global {{jsxref("Math")}} object to perform a wide variety of mathematical operations on numbers. +This chapter introduces the two most fundamental data types in JavaScript: numbers and strings. We will introduce their underlying representations, and functions used to work with and perform calculations on them. ## Numbers @@ -310,106 +310,120 @@ Choosing between BigInt and number depends on your use-case and your input's ran Read more about what you can do with BigInt values in the [Expressions and Operators](/en-US/docs/Web/JavaScript/Guide/Expressions_and_operators#bigint_operators) section, or the [BigInt reference](/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt). -## Date object +## Strings -JavaScript does not have a date data type. However, you can use the {{jsxref("Date")}} object and its methods to work with dates and times in your applications. The `Date` object has a large number of methods for setting, getting, and manipulating dates. It does not have any properties. +JavaScript's [String](/en-US/docs/Glossary/String) type is used to represent textual data. It is a set of "elements" of 16-bit unsigned integer values (UTF-16 code units). Each element in the String occupies a position in the String. The first element is at index 0, the next at index 1, and so on. The length of a String is the number of elements in it. You can create strings using string literals or string objects. -JavaScript handles dates similarly to Java. The two languages have many of the same date methods, and both languages store dates as the number of milliseconds since midnight at the beginning of January 1, 1970, UTC, with a Unix Timestamp being the number of seconds since the same instant. The instant at the midnight at the beginning of January 1, 1970, UTC is called the [epoch](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#the_epoch_timestamps_and_invalid_date). +### String literals -The `Date` object range is -100,000,000 days to 100,000,000 days relative to the epoch. +You can declare strings in source code using either single or double quotes: -To create a `Date` object: +```js-nolint +'foo' +"bar" +``` -```js -const dateObjectName = new Date([parameters]); +Within a string literal, most characters can be entered literally. The only exceptions are the backslash (`\`, which starts an escape sequence), the quote character being used to enclose the string, which terminates the string, and the newline character, which is a syntax error if not preceded by a backslash. + +More advanced strings can be created using escape sequences: + +#### Hexadecimal escape sequences + +The number after \x is interpreted as a [hexadecimal](https://en.wikipedia.org/wiki/Hexadecimal) number. + +```js-nolint +"\xA9" // "©" ``` -where `dateObjectName` is the name of the `Date` object being created; it can be a new object or a property of an existing object. +#### Unicode escape sequences -Calling `Date` without the `new` keyword returns a string representing the current date and time. +The Unicode escape sequences require at least four hexadecimal digits following `\u`. -The `parameters` in the preceding syntax can be any of the following: +```js-nolint +"\u00A9" // "©" +``` -- Nothing: creates today's date and time. For example, `today = new Date();`. -- A string representing a date, in many different forms. The exact forms supported differ among engines, but the following form is always supported: `YYYY-MM-DDTHH:mm:ss.sssZ`. For example, `xmas95 = new Date("1995-12-25")`. If you omit hours, minutes, or seconds, the value will be set to zero. -- A set of integer values for year, month, and day. For example, `xmas95 = new Date(1995, 11, 25)`. -- A set of integer values for year, month, day, hour, minute, and seconds. For example, `xmas95 = new Date(1995, 11, 25, 9, 30, 0);`. +#### Unicode code point escapes -### Methods of the Date object +With Unicode code point escapes, any character can be escaped using hexadecimal numbers so that it is possible to use Unicode code points up to `0x10FFFF`. With the four-digit Unicode escapes it is often necessary to write the surrogate halves separately to achieve the same result. -The `Date` object methods for handling dates and times fall into these broad categories: +See also {{jsxref("String.fromCodePoint()")}} or {{jsxref("String.prototype.codePointAt()")}}. -- "set" methods, for setting date and time values in `Date` objects. -- "get" methods, for getting date and time values from `Date` objects. -- "to" methods, for returning string values from `Date` objects. -- parse and UTC methods, for parsing `Date` strings. +```js-nolint +"\u{2F804}" -With the "get" and "set" methods you can get and set seconds, minutes, hours, day of the month, day of the week, months, and years separately. There is a `getDay` method that returns the day of the week, but no corresponding `setDay` method, because the day of the week is set automatically. These methods use integers to represent these values as follows: +// the same with simple Unicode escapes +"\uD87E\uDC04" +``` -- Seconds and minutes: 0 to 59 -- Hours: 0 to 23 -- Day: 0 (Sunday) to 6 (Saturday) -- Date: 1 to 31 (day of the month) -- Months: 0 (January) to 11 (December) -- Year: years since 1900 +## String object -For example, suppose you define the following date: +You can call methods directly on a string value: ```js -const xmas95 = new Date("1995-12-25"); +console.log("hello".toUpperCase()); // HELLO ``` -Then `xmas95.getMonth()` returns 11, and `xmas95.getFullYear()` returns 1995. +The following methods are available on {{jsxref("String")}} values: + +- Query: get the character or character code at a particular string index. Methods include {{jsxref("String/at", "at()")}}, {{jsxref("String/charAt", "charAt()")}}, {{jsxref("String/charCodeAt", "charCodeAt()")}}, and {{jsxref("String/codePointAt", "codePointAt()")}}. +- Search: get information about a substring that conforms to a pattern, or test if a particular substring exists. Methods include {{jsxref("String/indexOf", "indexOf()")}}, {{jsxref("String/lastIndexOf", "lastIndexOf()")}}, {{jsxref("String/startsWith", "startsWith()")}}, {{jsxref("String/endsWith", "endsWith()")}}, {{jsxref("String/includes", "includes()")}}, {{jsxref("String/match", "match()")}}, {{jsxref("String/matchAll", "matchAll()")}}, and {{jsxref("String/search", "search()")}} +- Composition: combine strings into a longer string. Methods include {{jsxref("String/padStart", "padStart()")}}, {{jsxref("String/padEnd", "padEnd()")}}, {{jsxref("String/concat", "concat()")}}, and {{jsxref("String/repeat", "repeat()")}}. +- Decomposition: break a string into smaller strings. Methods include {{jsxref("String/split", "split()")}}, {{jsxref("String/slice", "slice()")}}, {{jsxref("String/substring", "substring()")}}, {{jsxref("String/substr", "substr()")}}, {{jsxref("String/trim", "trim()")}}, {{jsxref("String/trimStart", "trimStart()")}}, and {{jsxref("String/trimEnd", "trimEnd()")}}. +- Transformation: return a new string based on the current string's content. Methods include {{jsxref("String/toLowerCase", "toLowerCase()")}}, {{jsxref("String/toUpperCase", "toUpperCase()")}}, {{jsxref("String/toLocaleLowerCase", "toLocaleLowerCase()")}}, {{jsxref("String/toLocaleUpperCase", "toLocaleUpperCase()")}}, {{jsxref("String/normalize", "normalize()")}}, and {{jsxref("String/toWellFormed", "toWellFormed()")}}. + +When working with strings, there are two other objects that provide important functionality for string manipulation: {{jsxref("RegExp")}} and {{jsxref("Intl")}}. They are introduced in [regular expressions](/en-US/docs/Web/JavaScript/Guide/Regular_Expressions) and [internationalization](/en-US/docs/Web/JavaScript/Guide/Internationalization) respectively. + +## Template literals + +[Template literals](/en-US/docs/Web/JavaScript/Reference/Template_literals) are string literals allowing embedded expressions. You can use multi-line strings and string interpolation features with them. -The `getTime` and `setTime` methods are useful for comparing dates. The `getTime` method returns the number of milliseconds since the epoch for a `Date` object. +Template literals are enclosed by backtick ([grave accent](https://en.wikipedia.org/wiki/Grave_accent)) characters (`` ` ``) instead of double or single quotes. Template literals can contain placeholders. These are indicated by the dollar sign and curly braces (`${expression}`). -For example, the following code displays the number of days left in the current year: +### Multi-lines + +Any new line characters inserted in the source are part of the template literal. Using normal strings, you would have to use the following syntax in order to get multi-line strings: ```js -const today = new Date(); -const endYear = new Date(1995, 11, 31, 23, 59, 59, 999); // Set day and month -endYear.setFullYear(today.getFullYear()); // Set year to this year -const msPerDay = 24 * 60 * 60 * 1000; // Number of milliseconds per day -let daysLeft = (endYear.getTime() - today.getTime()) / msPerDay; -daysLeft = Math.round(daysLeft); // Returns days left in the year +console.log( + "string text line 1\n\ +string text line 2", +); +// "string text line 1 +// string text line 2" ``` -This example creates a `Date` object named `today` that contains today's date. It then creates a `Date` object named `endYear` and sets the year to the current year. Then, using the number of milliseconds per day, it computes the number of days between `today` and `endYear`, using `getTime` and rounding to a whole number of days. - -The `parse` method is useful for assigning values from date strings to existing `Date` objects. For example, the following code uses `parse` and `setTime` to assign a date value to the `ipoDate` object: +To get the same effect with multi-line strings, you can now write: ```js -const ipoDate = new Date(); -ipoDate.setTime(Date.parse("Aug 9, 1995")); +console.log(`string text line 1 +string text line 2`); +// "string text line 1 +// string text line 2" ``` -### Example +### Embedded expressions -In the following example, the function `JSClock()` returns the time in the format of a digital clock. +In order to embed expressions within normal strings, you would use the following syntax: ```js -function JSClock() { - const time = new Date(); - const hour = time.getHours(); - const minute = time.getMinutes(); - const second = time.getSeconds(); - let temp = String(hour % 12); - if (temp === "0") { - temp = "12"; - } - temp += (minute < 10 ? ":0" : ":") + minute; - temp += (second < 10 ? ":0" : ":") + second; - temp += hour >= 12 ? " P.M." : " A.M."; - return temp; -} +const five = 5; +const ten = 10; +console.log( + "Fifteen is " + (five + ten) + " and not " + (2 * five + ten) + ".", +); +// "Fifteen is 15 and not 20." ``` -The `JSClock` function first creates a new `Date` object called `time`; since no arguments are given, time is created with the current date and time. Then calls to the `getHours`, `getMinutes`, and `getSeconds` methods assign the value of the current hour, minute, and second to `hour`, `minute`, and `second`. - -The following statements build a string value based on the time. The first statement creates a variable `temp`. Its value is `hour % 12`, which is `hour` in the 12-hour system. Then, if the hour is `0`, it gets re-assigned to `12`, so that midnights and noons are displayed as `12:00` instead of `0:00`. +Now, with template literals, you are able to make use of the syntactic sugar making substitutions like this more readable: -The next statement appends a `minute` value to `temp`. If the value of `minute` is less than 10, the conditional expression adds a string with a preceding zero; otherwise it adds a string with a demarcating colon. Then a statement appends a seconds value to `temp` in the same way. +```js +const five = 5; +const ten = 10; +console.log(`Fifteen is ${five + ten} and not ${2 * five + ten}.`); +// "Fifteen is 15 and not 20." +``` -Finally, a conditional expression appends "P.M." to `temp` if `hour` is 12 or greater; otherwise, it appends "A.M." to `temp`. +For more information, read about [Template literals](/en-US/docs/Web/JavaScript/Reference/Template_literals) in the [JavaScript reference](/en-US/docs/Web/JavaScript/Reference). -{{PreviousNext("Web/JavaScript/Guide/Expressions_and_operators", "Web/JavaScript/Guide/Text_formatting")}} +{{PreviousNext("Web/JavaScript/Guide/Expressions_and_operators", "Web/JavaScript/Guide/Representing_dates_times")}} diff --git a/files/en-us/web/javascript/guide/regular_expressions/index.md b/files/en-us/web/javascript/guide/regular_expressions/index.md index 07ab0d0913ab478..b49f40514e82984 100644 --- a/files/en-us/web/javascript/guide/regular_expressions/index.md +++ b/files/en-us/web/javascript/guide/regular_expressions/index.md @@ -4,7 +4,7 @@ slug: Web/JavaScript/Guide/Regular_expressions page-type: guide --- -{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Text_formatting", "Web/JavaScript/Guide/Indexed_collections")}} +{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Representing_dates_times", "Web/JavaScript/Guide/Indexed_collections")}} Regular expressions are patterns used to match character combinations in strings. In JavaScript, regular expressions are also objects. These patterns are used with the {{jsxref("RegExp/exec", "exec()")}} and {{jsxref("RegExp/test", "test()")}} methods of {{jsxref("RegExp")}}, and with the {{jsxref("String/match", "match()")}}, {{jsxref("String/matchAll", "matchAll()")}}, {{jsxref("String/replace", "replace()")}}, {{jsxref("String/replaceAll", "replaceAll()")}}, {{jsxref("String/search", "search()")}}, and {{jsxref("String/split", "split()")}} methods of {{jsxref("String")}}. @@ -456,4 +456,4 @@ form.addEventListener("submit", (event) => { - [Regex visualizer](https://extendsclass.com/regex-tester.html) - : An online visual regex tester. -{{PreviousNext("Web/JavaScript/Guide/Text_formatting", "Web/JavaScript/Guide/Indexed_collections")}} +{{PreviousNext("Web/JavaScript/Guide/Representing_dates_times", "Web/JavaScript/Guide/Indexed_collections")}} diff --git a/files/en-us/web/javascript/guide/representing_dates_times/index.md b/files/en-us/web/javascript/guide/representing_dates_times/index.md new file mode 100644 index 000000000000000..6626d35653cdc2c --- /dev/null +++ b/files/en-us/web/javascript/guide/representing_dates_times/index.md @@ -0,0 +1,111 @@ +--- +title: Representing dates & times +slug: Web/JavaScript/Guide/Representing_dates_times +page-type: guide +--- + +{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Numbers_and_strings", "Web/JavaScript/Guide/Regular_expressions")}} + +## Date object + +JavaScript does not have a date data type. However, you can use the {{jsxref("Date")}} object and its methods to work with dates and times in your applications. The `Date` object has a large number of methods for setting, getting, and manipulating dates. It does not have any properties. + +JavaScript handles dates similarly to Java. The two languages have many of the same date methods, and both languages store dates as the number of milliseconds since midnight at the beginning of January 1, 1970, UTC, with a Unix Timestamp being the number of seconds since the same instant. The instant at the midnight at the beginning of January 1, 1970, UTC is called the [epoch](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date#the_epoch_timestamps_and_invalid_date). + +The `Date` object range is -100,000,000 days to 100,000,000 days relative to the epoch. + +To create a `Date` object: + +```js +const dateObjectName = new Date([parameters]); +``` + +where `dateObjectName` is the name of the `Date` object being created; it can be a new object or a property of an existing object. + +Calling `Date` without the `new` keyword returns a string representing the current date and time. + +The `parameters` in the preceding syntax can be any of the following: + +- Nothing: creates today's date and time. For example, `today = new Date();`. +- A string representing a date, in many different forms. The exact forms supported differ among engines, but the following form is always supported: `YYYY-MM-DDTHH:mm:ss.sssZ`. For example, `xmas95 = new Date("1995-12-25")`. If you omit hours, minutes, or seconds, the value will be set to zero. +- A set of integer values for year, month, and day. For example, `xmas95 = new Date(1995, 11, 25)`. +- A set of integer values for year, month, day, hour, minute, and seconds. For example, `xmas95 = new Date(1995, 11, 25, 9, 30, 0);`. + +### Methods of the Date object + +The `Date` object methods for handling dates and times fall into these broad categories: + +- "set" methods, for setting date and time values in `Date` objects. +- "get" methods, for getting date and time values from `Date` objects. +- "to" methods, for returning string values from `Date` objects. +- parse and UTC methods, for parsing `Date` strings. + +With the "get" and "set" methods you can get and set seconds, minutes, hours, day of the month, day of the week, months, and years separately. There is a `getDay` method that returns the day of the week, but no corresponding `setDay` method, because the day of the week is set automatically. These methods use integers to represent these values as follows: + +- Seconds and minutes: 0 to 59 +- Hours: 0 to 23 +- Day: 0 (Sunday) to 6 (Saturday) +- Date: 1 to 31 (day of the month) +- Months: 0 (January) to 11 (December) +- Year: years since 1900 + +For example, suppose you define the following date: + +```js +const xmas95 = new Date("1995-12-25"); +``` + +Then `xmas95.getMonth()` returns 11, and `xmas95.getFullYear()` returns 1995. + +The `getTime` and `setTime` methods are useful for comparing dates. The `getTime` method returns the number of milliseconds since the epoch for a `Date` object. + +For example, the following code displays the number of days left in the current year: + +```js +const today = new Date(); +const endYear = new Date(1995, 11, 31, 23, 59, 59, 999); // Set day and month +endYear.setFullYear(today.getFullYear()); // Set year to this year +const msPerDay = 24 * 60 * 60 * 1000; // Number of milliseconds per day +let daysLeft = (endYear.getTime() - today.getTime()) / msPerDay; +daysLeft = Math.round(daysLeft); // Returns days left in the year +``` + +This example creates a `Date` object named `today` that contains today's date. It then creates a `Date` object named `endYear` and sets the year to the current year. Then, using the number of milliseconds per day, it computes the number of days between `today` and `endYear`, using `getTime` and rounding to a whole number of days. + +The `parse` method is useful for assigning values from date strings to existing `Date` objects. For example, the following code uses `parse` and `setTime` to assign a date value to the `ipoDate` object: + +```js +const ipoDate = new Date(); +ipoDate.setTime(Date.parse("Aug 9, 1995")); +``` + +### Example + +In the following example, the function `JSClock()` returns the time in the format of a digital clock. + +```js +function JSClock() { + const time = new Date(); + const hour = time.getHours(); + const minute = time.getMinutes(); + const second = time.getSeconds(); + let temp = String(hour % 12); + if (temp === "0") { + temp = "12"; + } + temp += (minute < 10 ? ":0" : ":") + minute; + temp += (second < 10 ? ":0" : ":") + second; + temp += hour >= 12 ? " P.M." : " A.M."; + return temp; +} +``` + +The `JSClock` function first creates a new `Date` object called `time`; since no arguments are given, time is created with the current date and time. Then calls to the `getHours`, `getMinutes`, and `getSeconds` methods assign the value of the current hour, minute, and second to `hour`, `minute`, and `second`. + +The following statements build a string value based on the time. The first statement creates a variable `temp`. Its value is `hour % 12`, which is `hour` in the 12-hour system. Then, if the hour is `0`, it gets re-assigned to `12`, so that midnights and noons are displayed as `12:00` instead of `0:00`. + +The next statement appends a `minute` value to `temp`. If the value of `minute` is less than 10, the conditional expression adds a string with a preceding zero; otherwise it adds a string with a demarcating colon. Then a statement appends a seconds value to `temp` in the same way. + +Finally, a conditional expression appends "P.M." to `temp` if `hour` is 12 or greater; otherwise, it appends "A.M." to `temp`. + +{{PreviousNext("Web/JavaScript/Guide/Numbers_and_strings", "Web/JavaScript/Guide/Regular_expressions")}} diff --git a/files/en-us/web/javascript/guide/text_formatting/index.md b/files/en-us/web/javascript/guide/text_formatting/index.md deleted file mode 100644 index 18a0fb312ee54f0..000000000000000 --- a/files/en-us/web/javascript/guide/text_formatting/index.md +++ /dev/null @@ -1,326 +0,0 @@ ---- -title: Text formatting -slug: Web/JavaScript/Guide/Text_formatting -page-type: guide ---- - -{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Numbers_and_dates", "Web/JavaScript/Guide/Regular_expressions")}} - -This chapter introduces how to work with strings and text in JavaScript. - -## Strings - -JavaScript's [String](/en-US/docs/Glossary/String) type is used to represent textual data. It is a set of "elements" of 16-bit unsigned integer values (UTF-16 code units). Each element in the String occupies a position in the String. The first element is at index 0, the next at index 1, and so on. The length of a String is the number of elements in it. You can create strings using string literals or string objects. - -### String literals - -You can declare strings in source code using either single or double quotes: - -```js-nolint -'foo' -"bar" -``` - -More advanced strings can be created using escape sequences: - -#### Hexadecimal escape sequences - -The number after \x is interpreted as a [hexadecimal](https://en.wikipedia.org/wiki/Hexadecimal) number. - -```js-nolint -"\xA9" // "©" -``` - -#### Unicode escape sequences - -The Unicode escape sequences require at least four hexadecimal digits following `\u`. - -```js-nolint -"\u00A9" // "©" -``` - -#### Unicode code point escapes - -With Unicode code point escapes, any character can be escaped using hexadecimal numbers so that it is possible to use Unicode code points up to `0x10FFFF`. With the four-digit Unicode escapes it is often necessary to write the surrogate halves separately to achieve the same result. - -See also {{jsxref("String.fromCodePoint()")}} or {{jsxref("String.prototype.codePointAt()")}}. - -```js-nolint -"\u{2F804}" - -// the same with simple Unicode escapes -"\uD87E\uDC04" -``` - -### String objects - -The {{jsxref("String")}} object is a wrapper around the string primitive data type. - -```js -const foo = new String("foo"); // Creates a String object -console.log(foo); // [String: 'foo'] -typeof foo; // 'object' -``` - -You can call any of the methods of the `String` object on a string literal value—JavaScript automatically converts the string literal to a temporary `String` object, calls the method, then discards the temporary `String` object. You can also use the `length` property with a string literal. - -You should use string literals unless you specifically need to use a `String` object, because `String` objects can have counterintuitive behavior. For example: - -```js -const firstString = "2 + 2"; // Creates a string literal value -const secondString = new String("2 + 2"); // Creates a String object -eval(firstString); // Returns the number 4 -eval(secondString); // Returns a String object containing "2 + 2" -``` - -A `String` object has one property, `length`, that indicates the number of UTF-16 code units in the string. For example, the following code assigns `helloLength` the value 13, because "Hello, World!" has 13 characters, each represented by one UTF-16 code unit. You can access each code unit using an array bracket style. You can't change individual characters because strings are immutable array-like objects: - -```js -const hello = "Hello, World!"; -const helloLength = hello.length; -hello[0] = "L"; // This has no effect, because strings are immutable -hello[0]; // This returns "H" -``` - -Characters whose Unicode scalar values are greater than U+FFFF (such as some rare Chinese/Japanese/Korean/Vietnamese characters and some emoji) are stored in UTF-16 with two surrogate code units each. For example, a string containing the single character U+1F600 "Emoji grinning face" will have length 2. Accessing the individual code units in such a string using square brackets may have undesirable consequences such as the formation of strings with unmatched surrogate code units, in violation of the Unicode standard. (Examples should be added to this page after MDN bug 857438 is fixed.) See also {{jsxref("String.fromCodePoint()")}} or {{jsxref("String.prototype.codePointAt()")}}. - -A `String` object has a variety of methods: for example those that return a variation on the string itself, such as `substring` and `toUpperCase`. - -The following table summarizes the methods of {{jsxref("String")}} objects. - -
Method | -Description | -
---|---|
- {{jsxref("String/charAt", "charAt()")}}, {{jsxref("String/charCodeAt", "charCodeAt()")}}, - {{jsxref("String/codePointAt", "codePointAt()")}} - | -- Return the character or character code at the specified position in - string. - | -
- {{jsxref("String/indexOf", "indexOf()")}}, - {{jsxref("String/lastIndexOf", "lastIndexOf()")}} - | -- Return the position of specified substring in the string or last - position of specified substring, respectively. - | -
- {{jsxref("String/startsWith", "startsWith()")}}, - {{jsxref("String/endsWith", "endsWith()")}}, - {{jsxref("String/includes", "includes()")}} - | -- Returns whether or not the string starts, ends or contains a specified - string. - | -
{{jsxref("String/concat", "concat()")}} | -Combines the text of two strings and returns a new string. | -
{{jsxref("String/split", "split()")}} | -
- Splits a String object into an array of strings by
- separating the string into substrings.
- |
-
{{jsxref("String/slice", "slice()")}} | -Extracts a section of a string and returns a new string. | -
- {{jsxref("String/substring", "substring()")}}, - {{jsxref("String/substr", "substr()")}} - | -- Return the specified subset of the string, either by specifying the - start and end indexes or the start index and a length. - | -
- {{jsxref("String/match", "match()")}}, {{jsxref("String/matchAll", "matchAll()")}}, - {{jsxref("String/replace", "replace()")}}, {{jsxref("String/replaceAll", "replaceAll()")}}, - {{jsxref("String/search", "search()")}} - | -Work with regular expressions. | -
- {{jsxref("String/toLowerCase", "toLowerCase()")}}, - {{jsxref("String/toUpperCase", "toUpperCase()")}} - | -
- - Return the string in all lowercase or all uppercase, respectively. - - |
-
{{jsxref("String/normalize", "normalize()")}} | -- Returns the Unicode Normalization Form of the calling string value. - | -
{{jsxref("String/repeat", "repeat()")}} | -- Returns a string consisting of the elements of the object repeated the - given times. - | -
{{jsxref("String/trim", "trim()")}} | -Trims whitespace from the beginning and end of the string. | -