Formatted output in javascript

Text formatting

This chapter introduces how to work with strings and text in JavaScript.

Strings

JavaScript’s 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 create simple strings using either single or double quotes:

More advanced strings can be created using escape sequences:

Hexadecimal escape sequences

The number after \x is interpreted as a hexadecimal number.

Unicode escape sequences

The Unicode escape sequences require at least four hexadecimal digits following \u .

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 simple Unicode escapes it is often necessary to write the surrogate halves separately to achieve the same result.

"\u" // the same with simple Unicode escapes "\uD87E\uDC04" 

String objects

The String object is a wrapper around the string primitive data type.

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:

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:

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 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 String.fromCodePoint() or 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 String objects.

Methods of String

Method Description charAt() , charCodeAt() , codePointAt() Return the character or character code at the specified position in string. indexOf() , lastIndexOf() Return the position of specified substring in the string or last position of specified substring, respectively. startsWith() , endsWith() , includes() Returns whether or not the string starts, ends or contains a specified string. concat() Combines the text of two strings and returns a new string. split() Splits a String object into an array of strings by separating the string into substrings. slice() Extracts a section of a string and returns a new string. substring() , substr() Return the specified subset of the string, either by specifying the start and end indexes or the start index and a length. match() , matchAll() , replace() , replaceAll() , search() Work with regular expressions. toLowerCase() , toUpperCase()

Return the string in all lowercase or all uppercase, respectively.

Multi-line template literals

Template literals are string literals allowing embedded expressions. You can use multi-line strings and string interpolation features with them.

Template literals are enclosed by backtick (grave accent) characters ( ` ) instead of double or single quotes. Template literals can contain placeholders. These are indicated by the dollar sign and curly braces ( $ ).

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:

.log( "string text line 1\n\ string text line 2", ); // "string text line 1 // string text line 2" 

To get the same effect with multi-line strings, you can now write:

.log(`string text line 1 string text line 2`); // "string text line 1 // string text line 2" 

Embedded expressions

In order to embed expressions within normal strings, you would use the following syntax:

const five = 5; const ten = 10; console.log( "Fifteen is " + (five + ten) + " and not " + (2 * five + ten) + ".", ); // "Fifteen is 15 and not 20." 

Now, with template literals, you are able to make use of the syntactic sugar making substitutions like this more readable:

const five = 5; const ten = 10; console.log(`Fifteen is $five + ten> and not $2 * five + ten>.`); // "Fifteen is 15 and not 20." 

For more information, read about Template literals in the JavaScript reference.

Internationalization

The Intl object is the namespace for the ECMAScript Internationalization API, which provides language sensitive string comparison, number formatting, and date and time formatting. The constructors for Intl.Collator , Intl.NumberFormat , and Intl.DateTimeFormat objects are properties of the Intl object.

Date and time formatting

The 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.)

// 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 Intl.NumberFormat object is useful for formatting numbers, for example currencies.

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 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.

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).

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" 

Found a content problem with this page?

This page was last modified on Apr 5, 2023 by MDN contributors.

Your blueprint for a better internet.

Источник

Beyond console.log(): 3 Ways to Format Console Outputs in JavaScript

As JavaScript developers, we intuitively use console.log() to debug, print out variables, and log results of our current operations to make sure we are on the right programming path. Indeed, console.log() seems powerful enough, but did you know there are other cool methods in the Console API that can also make your life easier? Recently I came across console.table() in a tutorial, which prompted me to investigate alternative approaches to the plain-old console.log(). Here are 3 formatting tools that I have added to my debugging toolkit:

1. console.table()

As the name suggests, console.table() prints your output in a nicely formatted table, instead of a cluster of text from console.log() . Let’s say we have an array of objects, each object containing multiple key-value pairs:

const inventors = [  first: 'Albert', last: 'Einstein', year: 1879, passed: 1955 >,  first: 'Isaac', last: 'Newton', year: 1643, passed: 1727 >,  first: 'Galileo', last: 'Galilei', year: 1564, passed: 1642 >,  first: 'Marie', last: 'Curie', year: 1867, passed: 1934 >,  first: 'Johannes', last: 'Kepler', year: 1571, passed: 1630 >,  first: 'Nicolaus', last: 'Copernicus', year: 1473, passed: 1543 >,  first: 'Max', last: 'Planck', year: 1858, passed: 1947 >,  first: 'Katherine', last: 'Blodgett', year: 1898, passed: 1979 >,  first: 'Ada', last: 'Lovelace', year: 1815, passed: 1852 >,  first: 'Sarah E.', last: 'Goode', year: 1855, passed: 1905 >,  first: 'Lise', last: 'Meitner', year: 1878, passed: 1968 >,  first: 'Hanna', last: 'Hammarström', year: 1829, passed: 1909 > ] 
┌─────────┬─────────────┬───────────────┬──────┬────────┐  (index)  first  last  year  passed  ├─────────┼─────────────┼───────────────┼──────┼────────┤  0  'Albert'  'Einstein'  1879  1955   1  'Isaac'  'Newton'  1643  1727   2  'Galileo'  'Galilei'  1564  1642   3  'Marie'  'Curie'  1867  1934   4  'Johannes'  'Kepler'  1571  1630   5  'Nicolaus'  'Copernicus'  1473  1543   6  'Max'  'Planck'  1858  1947   7  'Katherine'  'Blodgett'  1898  1979   8  'Ada'  'Lovelace'  1815  1852   9  'Sarah E.'  'Goode'  1855  1905   10  'Lise'  'Meitner'  1878  1968   11  'Hanna'  'Hammarström'  1829  1909  └─────────┴─────────────┴───────────────┴──────┴────────┘ 

2. console.group() and console.groupEnd()

This pair of console methods allow you to create a hierarchical structure of your output. If you have a group of related data, you can wrap them inside console.group() and console.groupEnd() , like so:

console.group('Meat') console.log('Chicken') console.log('Pork') console.log('Beef') console.groupEnd('Meat') console.group('Veggies') console.log('Corn') console.log('Spinach') console.log('Carrots') console.groupEnd('Veggies') console.group('Fruits') console.log('Apple') console.log('Banana') console.log('Tomato') console.groupEnd('Fruits') 

. and you will see a beautifully grouped set of output (feel free to try on a Chrome or Firefox console, it looks even prettier in my opinion):

Meat Chicken Pork Beef Veggies Corn Spinach Carrots Fruits Apple Banana Tomato 

3. console.dir()

This one may or may not be as useful, depending on the browser you’re on. Essentially, console.dir() prints out a hierarchical list of properties inside the specified JavaScript project. For example, open your browser console and try console.dir() by passing in the following object:

const food =  'Meat':  'Chicken': ['grilled', 'fried'], 'Pork': ['BBQ', 'steamed'], 'Beef': ['medium', 'rare'] >, 'Veggies':  'Corn': ['white', 'yellow'], 'Spinach': ['regular', 'baby-size'], 'Carrots': ['regular', 'bite-size'] >, 'Fruits':  'Apple': ['green', 'red'], 'Banana': ['raw', 'ripe'], 'Tomato': ['big', 'small'] >, > 

In the Chrome console, you can see that console.dir(food) makes it easier to spot the data type than does console.log(food) . Whereas in Firefox, both outputs appear the same. Nonetheless, if you click on the triangle at the start of the output, both console.dir() and console.log() display nicely formatted JavaScript objects, neatly organized by property types and their values. If you are already familiar with those three methods, I recommend checking out the following resources, experiment on each method mentioned in the articles, and let me know which ones you plan on using regularly. Happy debugging!

Resources:

Источник

Читайте также:  Blob object in java
Оцените статью