Please note, this is a STATIC archive of website developer.mozilla.org from 03 Nov 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

Revision 798097 of Text formatting

  • Revision slug: Web/JavaScript/Guide/Text_formatting
  • Revision title: Text formatting
  • Revision id: 798097
  • Created:
  • Creator: xfq
  • Is current revision? No
  • Comment Typo fix.
Tags: 

Revision Content

{{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 {{Glossary("String")}} type is used to represent textual data. It is a set of "elements" of 16-bit unsigned integer values. 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:

'foo'
"bar"

More advanced strings can be created using escape sequences:

Hexadecimal escape sequences

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

'\xA9' // "©"

Unicode escape sequences

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

'\u00A9' // "©"

Unicode code point escapes

New in ECMAScript 6. 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.

See also {{jsxref("String.fromCodePoint()")}} or {{jsxref("String.prototype.codePointAt()")}}.

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

var s = new String("foo"); // Creates a String object
console.log(s); // Displays: { '0': 'f', '1': 'o', '2': 'o'}
typeof s; // Returns '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 String.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:

var s1 = "2 + 2"; // Creates a string literal value
var s2 = new String("2 + 2"); // Creates a String object
eval(s1); // Returns the number 4
eval(s2); // Returns the string "2 + 2"

A String object has one property, length, that indicates the number of characters in the string. For example, the following code assigns x the value 13, because "Hello, World!" has 13 characters:

var mystring = "Hello, World!";
var x = mystring.length;

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.

Methods of String

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.fromCharCode", "fromCharCode")}}, {{jsxref("String.fromCodePoint", "fromCodePoint")}} Constructs a string from the specified sequence of Unicode values. This is a method of the String class, not a String instance.
{{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.replace", "replace")}}, {{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.

Multi-line template strings

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

Template strings are enclosed by the back-tick (` `) (grave accent) character instead of double or single quotes. Template strings can contain place holders. These are indicated by the Dollar sign and curly braces (${expression}).

Multi-lines

Any new line characters inserted in the source are part of the template string. Using normal strings, you would have to use the following syntax in order to get multi-line strings:

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

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

var a = 5;
var b = 10;
console.log("Fifteen is " + (a + b) + " and\nnot " + (2 * a + b) + ".");
// "Fifteen is 15 and
// not 20."

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

var a = 5;
var b = 10;
console.log(`Fifteen is ${a + b} and\nnot ${2 * a + b}.`);
// "Fifteen is 15 and
// not 20."

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

Internationalization

The {{jsxref("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 {{jsxref("Collator")}}, {{jsxref("NumberFormat")}}, and {{jsxref("DateTimeFormat")}} objects are properties of the Intl object.

Date and time formatting

The {{jsxref("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.)

var msPerDay = 24 * 60 * 60 * 1000;
 
// July 17, 2014 00:00:00 UTC.
var july172014 = new Date(msPerDay * (44 * 365 + 11 + 197));

var options = { year: "2-digit", month: "2-digit", day: "2-digit",
                hour: "2-digit", minute: "2-digit", timeZoneName: "short" };
var americanDateTime = new Intl.DateTimeFormat("en-US", options).format;
 
console.log(americanDateTime(july172014)); // 07/16/14, 5:00 PM PDT

Number formatting

The {{jsxref("NumberFormat")}} object is useful for formatting numbers, for example currencies.

var gasPrice = new Intl.NumberFormat("en-US",
                        { style: "currency", currency: "USD",
                          minimumFractionDigits: 3 });
 
console.log(gasPrice.format(5.259)); // $5.259

var hanDecimalRMBInChina = new Intl.NumberFormat("zh-CN-u-nu-hanidec",
                        { style: "currency", currency: "CNY" });
 
console.log(hanDecimalRMBInChina.format(1314.25)); // ¥ 一,三一四.二五

Collation

The {{jsxref("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.

var names = ["Hochberg", "Hönigswald", "Holzman"];
 
var germanPhonebook = new Intl.Collator("de-DE-u-co-phonebk");
 
// as if sorting ["Hochberg", "Hoenigswald", "Holzman"]:
console.log(names.sort(germanPhonebook.compare).join(", "));
// logs "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).

var germanDictionary = new Intl.Collator("de-DE-u-co-dict");
 
// as if sorting ["Hochberg", "Honigswald", "Holzman"]:
console.log(names.sort(germanDictionary.compare).join(", "));
// logs "Hochberg, Holzman, Hönigswald"

For more information about the {{jsxref("Intl")}} API, see also Introducing the JavaScript Internationalization API.

Regular expressions

{{Glossary("Regular_expression", "Regular expressions")}} are patterns used to match character combinations in strings. They can be powerful and complex and are described in an own chapter. Read more about regular expressions here:

{{PreviousNext("Web/JavaScript/Guide/Numbers_and_dates", "Web/JavaScript/Guide/Regular_Expressions")}}

Revision Source

<div>{{jsSidebar("JavaScript Guide")}} {{PreviousNext("Web/JavaScript/Guide/Numbers_and_dates", "Web/JavaScript/Guide/Regular_Expressions")}}</div>

<p class="summary">This chapter introduces how to work with strings and text in JavaScript.</p>

<h2 id="Strings">Strings</h2>

<p>JavaScript's {{Glossary("String")}} type is used to represent textual data. It is a set of "elements" of 16-bit unsigned integer values. 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.</p>

<h3 id="String_literals">String literals</h3>

<p>You can create simple strings using either single or double quotes:</p>

<pre class="brush: js">
'foo'
"bar"</pre>

<p>More advanced strings can be created using escape sequences:</p>

<h4 id="Hexadecimal_escape_sequences">Hexadecimal escape sequences</h4>

<p>The number after \x is interpreted as a <a href="https://en.wikipedia.org/wiki/Hexadecimal">hexadecimal</a> number.</p>

<pre class="brush: js">
'\xA9' // "©"
</pre>

<h4 id="Unicode_escape_sequences">Unicode escape sequences</h4>

<p>The Unicode escape sequences require at least four characters following <code>\u</code>.</p>

<pre class="brush: js">
'\u00A9' // "©"</pre>

<h4 id="Unicode_code_point_escapes">Unicode code point escapes</h4>

<p>New in ECMAScript 6. 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 <code>0x10FFFF</code>. With simple Unicode escapes it is often necessary to write the surrogate halves separately to achieve the same.</p>

<p>See also {{jsxref("String.fromCodePoint()")}} or {{jsxref("String.prototype.codePointAt()")}}.</p>

<pre class="brush: js">
'\u{2F804}'

// the same with simple Unicode escapes
'\uD87E\uDC04'</pre>

<h3 id="String_objects">String objects</h3>

<p>The {{jsxref("String")}} object is a wrapper around the string primitive data type.</p>

<pre class="brush: js">
var s = new String("foo"); // Creates a String object
console.log(s); // Displays: { '0': 'f', '1': 'o', '2': 'o'}
typeof s; // Returns 'object'
</pre>

<p>You can call any of the methods of the <code>String</code> object on a string literal value—JavaScript automatically converts the string literal to a temporary <code>String</code> object, calls the method, then discards the temporary <code>String</code> object. You can also use the <code>String.length</code> property with a string literal.</p>

<p>You should use string literals unless you specifically need to use a <code>String</code> object, because <code>String</code> objects can have counterintuitive behavior. For example:</p>

<pre class="brush: js">
var s1 = "2 + 2"; // Creates a string literal value
var s2 = new String("2 + 2"); // Creates a String object
eval(s1); // Returns the number 4
eval(s2); // Returns the string "2 + 2"</pre>

<p>A <code>String</code> object has one property, <code>length</code>, that indicates the number of characters in the string. For example, the following code assigns <code>x</code> the value 13, because "Hello, World!" has 13 characters:</p>

<pre class="brush: js">
var mystring = "Hello, World!";
var x = mystring.length;
</pre>

<p>A <code>String</code> object has a variety of methods: for example those that return a variation on the string itself, such as <code>substring</code> and <code>toUpperCase</code>.</p>

<p>The following table summarizes the methods of {{jsxref("String")}} objects.</p>

<table class="standard-table">
 <caption>
 <h4 id="Methods_of_String">Methods of <code>String</code></h4>
 </caption>
 <thead>
  <tr>
   <th scope="col">Method</th>
   <th scope="col">Description</th>
  </tr>
 </thead>
 <tbody>
  <tr>
   <td>{{jsxref("String.charAt", "charAt")}},&nbsp;{{jsxref("String.charCodeAt", "charCodeAt")}}, {{jsxref("String.codePointAt", "codePointAt")}}</td>
   <td>Return the character or character code at the specified position in string.</td>
  </tr>
  <tr>
   <td>{{jsxref("String.indexOf", "indexOf")}}, {{jsxref("String.lastIndexOf", "lastIndexOf")}}</td>
   <td>Return the position of specified substring in the string or last position of specified substring, respectively.</td>
  </tr>
  <tr>
   <td>{{jsxref("String.startsWith", "startsWith")}}, {{jsxref("String.endsWith", "endsWith")}}, {{jsxref("String.includes", "includes")}}</td>
   <td>Returns whether or not the string starts, ends or contains a specified string.</td>
  </tr>
  <tr>
   <td>{{jsxref("String.concat", "concat")}}</td>
   <td>Combines the text of two strings and returns a new string.</td>
  </tr>
  <tr>
   <td>{{jsxref("String.fromCharCode", "fromCharCode")}}, {{jsxref("String.fromCodePoint", "fromCodePoint")}}</td>
   <td>Constructs a string from the specified sequence of Unicode values. This is a method of the String class, not a String instance.</td>
  </tr>
  <tr>
   <td>{{jsxref("String.split", "split")}}</td>
   <td>Splits a <code>String</code> object into an array of strings by separating the string into substrings.</td>
  </tr>
  <tr>
   <td>{{jsxref("String.slice", "slice")}}</td>
   <td>Extracts a section of a string and returns a new string.</td>
  </tr>
  <tr>
   <td>{{jsxref("String.substring", "substring")}}, {{jsxref("String.substr", "substr")}}</td>
   <td>Return the specified subset of the string, either by specifying the start and end indexes or the start index and a length.</td>
  </tr>
  <tr>
   <td>{{jsxref("String.match", "match")}}, {{jsxref("String.replace", "replace")}}, {{jsxref("String.search", "search")}}</td>
   <td>Work with regular expressions.</td>
  </tr>
  <tr>
   <td>{{jsxref("String.toLowerCase", "toLowerCase")}}, {{jsxref("String.toUpperCase", "toUpperCase")}}</td>
   <td>
    <p>Return the string in all lowercase or all uppercase, respectively.</p>
   </td>
  </tr>
  <tr>
   <td>{{jsxref("String.normalize", "normalize")}}</td>
   <td>Returns the Unicode Normalization Form of the calling string value.</td>
  </tr>
  <tr>
   <td>{{jsxref("String.repeat", "repeat")}}</td>
   <td>Returns a string consisting of the elements of the object repeated the given times.</td>
  </tr>
  <tr>
   <td>{{jsxref("String.trim", "trim")}}</td>
   <td>Trims whitespace from the beginning and end of the string.</td>
  </tr>
 </tbody>
</table>

<h3 id="Multi-line_template_strings">Multi-line template strings</h3>

<p><a href="/en-US/docs/Web/JavaScript/Reference/template_strings">Template strings</a> are string literals allowing embedded expressions. You can use multi-line strings and string interpolation features with them.</p>

<p>Template strings are enclosed by the back-tick (` `) (<a class="external external-icon" href="https://en.wikipedia.org/wiki/Grave_accent">grave accent</a>) character instead of double or single quotes. Template strings can contain place holders. These are indicated by the Dollar sign and curly braces (<code>${expression}</code>).</p>

<h4 id="Multi-lines">Multi-lines</h4>

<p>Any new line characters inserted in the source are part of the template string. Using normal strings, you would have to use the following syntax in order to get multi-line strings:</p>

<pre class="brush: js">
console.log("string text line 1\n\
string text line 2");
// "string text line 1
// string text line 2"</pre>

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

<pre class="brush: js">
console.log(`string text line 1
string text line 2`);
// "string text line 1
// string text line 2"</pre>

<h4 id="Embedded_expressions">Embedded expressions</h4>

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

<pre class="brush: js">
var a = 5;
var b = 10;
console.log("Fifteen is " + (a + b) + " and\nnot " + (2 * a + b) + ".");
// "Fifteen is 15 and
// not 20."</pre>

<p>Now, with template strings, you are able to make use of the syntactic sugar making substitutions like this more readable:</p>

<pre class="brush: js">
var a = 5;
var b = 10;
console.log(`Fifteen is ${a + b} and\nnot ${2 * a + b}.`);
// "Fifteen is 15 and
// not 20."</pre>

<p>For more information, read about <a href="/en-US/docs/Web/JavaScript/Reference/template_strings">Template strings</a> in the <a href="/en-US/docs/Web/JavaScript/Reference">JavaScript reference</a>.</p>

<h2 id="Internationalization">Internationalization</h2>

<p>The {{jsxref("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 {{jsxref("Collator")}}, {{jsxref("NumberFormat")}}, and {{jsxref("DateTimeFormat")}} objects are properties of the <code>Intl</code> object.</p>

<h3 id="Date_and_time_formatting">Date and time formatting</h3>

<p>The {{jsxref("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.)</p>

<pre class="brush: js">
var msPerDay = 24 * 60 * 60 * 1000;
 
// July 17, 2014 00:00:00 UTC.
var july172014 = new Date(msPerDay * (44 * 365 + 11 + 197));

var options = { year: "2-digit", month: "2-digit", day: "2-digit",
&nbsp;&nbsp;&nbsp;             hour: "2-digit", minute: "2-digit", timeZoneName: "short" };
var americanDateTime = new Intl.DateTimeFormat("en-US", options).format;
&nbsp;
console.log(americanDateTime(july172014)); // 07/16/14, 5:00 PM PDT
</pre>

<h3 id="Number_formatting">Number formatting</h3>

<p>The {{jsxref("NumberFormat")}} object is useful for formatting numbers, for example currencies.</p>

<pre class="brush: js">
var gasPrice = new Intl.NumberFormat("en-US",
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; { style: "currency", currency: "USD",
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; minimumFractionDigits: 3 });
&nbsp;
console.log(gasPrice.format(5.259)); // $5.259

var hanDecimalRMBInChina = new Intl.NumberFormat("zh-CN-u-nu-hanidec",
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; { style: "currency", currency: "CNY" });
&nbsp;
console.log(hanDecimalRMBInChina.format(1314.25)); // ¥ 一,三一四.二五
</pre>

<h3 id="Collation">Collation</h3>

<p>The {{jsxref("Collator")}} object is useful for comparing and sorting strings.</p>

<p>For example, there are actually two different sort orders in German, <em>phonebook</em> and <em>dictionary</em>. Phonebook sort emphasizes sound, and it’s as if “ä”, “ö”, and so on were expanded to “ae”, “oe”, and so on prior to sorting.</p>

<pre class="brush: js">
var names = ["Hochberg", "Hönigswald", "Holzman"];
&nbsp;
var germanPhonebook = new Intl.Collator("de-DE-u-co-phonebk");
&nbsp;
// as if sorting ["Hochberg", "Hoenigswald", "Holzman"]:
console.log(names.sort(germanPhonebook.compare).join(", "));
// logs "Hochberg, Hönigswald, Holzman"
</pre>

<p>Some German words conjugate with extra umlauts, so in dictionaries it’s sensible to order ignoring umlauts (except when ordering words differing <em>only</em> by umlauts: <em>schon</em> before <em>schön</em>).</p>

<pre class="brush: js">
var germanDictionary = new Intl.Collator("de-DE-u-co-dict");
&nbsp;
// as if sorting ["Hochberg", "Honigswald", "Holzman"]:
console.log(names.sort(germanDictionary.compare).join(", "));
// logs "Hochberg, Holzman, Hönigswald"
</pre>

<p>For more information about the {{jsxref("Intl")}} API, see also <a href="https://hacks.mozilla.org/2014/12/introducing-the-javascript-internationalization-api/">Introducing the JavaScript Internationalization API</a>.</p>

<h2 id="Regular_expressions">Regular expressions</h2>

<p>{{Glossary("Regular_expression", "Regular expressions")}} are patterns used to match character combinations in strings. They can be powerful and complex and are described in an own chapter. Read more about regular expressions here:</p>

<ul>
 <li><a href="/en-US/docs/Web/JavaScript/Guide/Regular_Expressions">JavaScript regular expressions</a> in the JavaScript guide.</li>
 <li>{{jsxref("RegExp")}} reference documentation.</li>
</ul>

<div>{{PreviousNext("Web/JavaScript/Guide/Numbers_and_dates", "Web/JavaScript/Guide/Regular_Expressions")}}</div>
Revert to this revision