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

字符串

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

CAUTION: if you edit this page, do not include any characters above U+FFFF, until MDN bug 857438 is fixed ( https://bugzilla.mozilla.org/show_bug.cgi?id=857438 ).

字符串文字

You can create simple strings using either single or double quotes:

'foo'
"bar"
					

More advanced strings can be created using escape sequences:

十六进制转义序列

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

'\xA9' // "©"
					

Unicode 转义序列

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

'\u00A9' // "©"
					

Unicode 代码点转义

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

另请参阅 String.fromCodePoint() or String.prototype.codePointAt() .

'\u{2F804}'
// the same with simple Unicode escapes
'\uD87E\uDC04'
					

字符串对象

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

const foo = new String('foo'); // Creates a String object
console.log(foo); // Displays: [String: 'foo']
typeof foo; // 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:

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 the string "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 对象。

Methods of String

Method 描述
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.
fromCharCode , fromCodePoint Constructs a string from the specified sequence of Unicode values. This is a method of the String class, not a String instance.
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.
normalize Returns the Unicode Normalization Form of the calling string value.
repeat Returns a string consisting of the elements of the object repeated the given times.
trim Trims whitespace from the beginning and end of the string.

多行模板文字

模板文字 are string literals allowing embedded expressions. You can use multi-line strings and string interpolation features with them.

Template literals are enclosed by the back-tick (` `) ( grave accent ) character instead of double or single quotes. Template literals 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 literal. 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:

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

了解更多信息,阅读关于 模板文字 JavaScript 参考 .

国际化

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 Collator , NumberFormat ,和 DateTimeFormat objects are properties of 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.)

const msPerDay = 24 * 60 * 60 * 1000;
// July 17, 2014 00:00:00 UTC.
const july172014 = new Date(msPerDay * (44 * 365 + 11 + 197));
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;
console.log(americanDateTime(july172014)); // 07/16/14, 5:00 PM PDT
					

数字格式化

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

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(', '));
// 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 ).

const 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"
					

更多信息有关 Intl API,另请参阅 引入 JavaScript 国际化 API .

元数据

  1. JavaScript
  2. 教程:
  3. 完全初学者
    1. JavaScript 基础
    2. JavaScript 第一步
    3. JavaScript 构建块
    4. 引入 JavaScript 对象
  4. JavaScript 指南
    1. 介绍
    2. 语法和类型
    3. 控制流程和错误处理
    4. 循环和迭代
    5. 函数
    6. 表达式和运算符
    7. 数字和日期
    8. 文本格式化
    9. 正则表达式
    10. 索引集合
    11. 键控集合
    12. Working with objects
    13. 对象模型的细节
    14. Using promises
    15. 迭代器和生成器
    16. Meta programming
    17. JavaScript 模块
  5. 中间体
    1. Client-side JavaScript frameworks
    2. 客户端侧 Web API
    3. 重新介绍 JavaScript
    4. JavaScript 数据结构
    5. 相等比较和相同
    6. 闭包
  6. 高级
    1. 继承和原型链
    2. 严格模式
    3. JavaScript 类型数组
    4. 内存管理
    5. 并发模型和事件循环
  7. 参考:
  8. 内置对象
    1. AggregateError
    2. Array
    3. ArrayBuffer
    4. AsyncFunction
    5. Atomics
    6. BigInt
    7. BigInt64Array
    8. BigUint64Array
    9. 布尔
    10. DataView
    11. Date
    12. Error
    13. EvalError
    14. Float32Array
    15. Float64Array
    16. Function
    17. Generator
    18. GeneratorFunction
    19. Infinity
    20. Int16Array
    21. Int32Array
    22. Int8Array
    23. InternalError
    24. Intl
    25. JSON
    26. Map
    27. Math
    28. NaN
    29. Number
    30. Object
    31. Promise
    32. Proxy
    33. RangeError
    34. ReferenceError
    35. Reflect
    36. RegExp
    37. Set
    38. SharedArrayBuffer
    39. String
    40. Symbol
    41. SyntaxError
    42. TypeError
    43. TypedArray
    44. URIError
    45. Uint16Array
    46. Uint32Array
    47. Uint8Array
    48. Uint8ClampedArray
    49. WeakMap
    50. WeakSet
    51. WebAssembly
    52. decodeURI()
    53. decodeURIComponent()
    54. encodeURI()
    55. encodeURIComponent()
    56. escape()
    57. eval()
    58. globalThis
    59. isFinite()
    60. isNaN()
    61. null
    62. parseFloat()
    63. parseInt()
    64. undefined
    65. unescape()
    66. uneval()
  9. 表达式 & 运算符
    1. 算术运算符
    2. 赋值运算符
    3. Bitwise operators
    4. 逗号运算符
    5. Comparison operators
    6. 条件 (三元) 运算符
    7. Destructuring assignment
    8. 函数表达式
    9. Grouping operator
    10. Logical operators
    11. Nullish coalescing operator
    12. 对象初始化器
    13. 运算符优先级
    14. Optional chaining
    15. Pipeline operator
    16. 特性访问器
    17. 传播句法
    18. 异步函数表达式
    19. await
    20. class expression
    21. delete operator
    22. function* 表达式
    23. in operator
    24. instanceof
    25. new operator
    26. new.target
    27. super
    28. this
    29. typeof
    30. void 运算符
    31. yield
    32. yield*
  10. 语句 & 声明
    1. async function
    2. block
    3. break
    4. class
    5. const
    6. continue
    7. debugger
    8. do...while
    9. empty
    10. export
    11. for
    12. for await...of
    13. for...in
    14. for...of
    15. 函数声明
    16. function*
    17. if...else
    18. import
    19. import.meta
    20. label
    21. let
    22. return
    23. switch
    24. throw
    25. try...catch
    26. var
    27. while
    28. with
  11. 函数
    1. 箭头函数表达式
    2. 默认参数
    3. 方法定义
    4. 其余参数
    5. 自变量对象
    6. getter
    7. setter
    1. Class fields
    2. 构造函数
    3. extends
    4. static
  12. 错误
    1. Error: Permission denied to access property "x"
    2. InternalError: too much recursion
    3. RangeError: argument is not a valid code point
    4. RangeError: invalid array length
    5. RangeError: invalid date
    6. RangeError: precision is out of range
    7. RangeError: radix must be an integer
    8. RangeError: repeat count must be less than infinity
    9. RangeError: repeat count must be non-negative
    10. ReferenceError: "x" is not defined
    11. ReferenceError: assignment to undeclared variable "x"
    12. ReferenceError: can't access lexical declaration`X' before initialization
    13. ReferenceError: deprecated caller or arguments usage
    14. ReferenceError: invalid assignment left-hand side
    15. ReferenceError: reference to undefined property "x"
    16. SyntaxError: "0"-prefixed octal literals and octal escape seq. are deprecated
    17. SyntaxError: "use strict" not allowed in function with non-simple parameters
    18. SyntaxError: "x" is a reserved identifier
    19. SyntaxError: JSON.parse: bad parsing
    20. SyntaxError: Malformed formal parameter
    21. SyntaxError: Unexpected token
    22. SyntaxError: Using //@ to indicate sourceURL pragmas is deprecated. Use //# instead
    23. SyntaxError: a declaration in the head of a for-of loop can't have an initializer
    24. SyntaxError: applying the 'delete' operator to an unqualified name is deprecated
    25. SyntaxError: for-in loop head declarations may not have initializers
    26. SyntaxError: function statement requires a name
    27. SyntaxError: identifier starts immediately after numeric literal
    28. SyntaxError: illegal character
    29. SyntaxError: invalid regular expression flag "x"
    30. SyntaxError: missing ) after argument list
    31. SyntaxError: missing ) after condition
    32. SyntaxError: missing : after property id
    33. SyntaxError: missing ; before statement
    34. SyntaxError: missing = in const declaration
    35. SyntaxError: missing ] after element list
    36. SyntaxError: missing formal parameter
    37. SyntaxError: missing name after . operator
    38. SyntaxError: missing variable name
    39. SyntaxError: missing } after function body
    40. SyntaxError: missing } after property list
    41. SyntaxError: redeclaration of formal parameter "x"
    42. SyntaxError: return not in function
    43. SyntaxError: test for equality (==) mistyped as assignment (=)?
    44. SyntaxError: unterminated string literal
    45. TypeError: "x" has no properties
    46. TypeError: "x" is (not) "y"
    47. TypeError: "x" is not a constructor
    48. TypeError: "x" is not a function
    49. TypeError: "x" is not a non-null object
    50. TypeError: "x" is read-only
    51. TypeError: 'x' is not iterable
    52. TypeError: More arguments needed
    53. TypeError: Reduce of empty array with no initial value
    54. TypeError: X.prototype.y called on incompatible type
    55. TypeError: can't access dead object
    56. TypeError: can't access property "x" of "y"
    57. TypeError: can't assign to property "x" on "y": not an object
    58. TypeError: can't define property "x": "obj" is not extensible
    59. TypeError: can't delete non-configurable array element
    60. TypeError: can't redefine non-configurable property "x"
    61. TypeError: cannot use 'in' operator to search for 'x' in 'y'
    62. TypeError: cyclic object value
    63. TypeError: invalid 'instanceof' operand 'x'
    64. TypeError: invalid Array.prototype.sort argument
    65. TypeError: invalid arguments
    66. TypeError: invalid assignment to const "x"
    67. TypeError: property "x" is non-configurable and can't be deleted
    68. TypeError: setting getter-only property "x"
    69. TypeError: variable "x" redeclares argument
    70. URIError: malformed URI sequence
    71. Warning: -file- is being assigned a //# sourceMappingURL, but already has one
    72. Warning: 08/09 is not a legal ECMA-262 octal constant
    73. Warning: Date.prototype.toLocaleFormat is deprecated
    74. Warning: JavaScript 1.6's for-each-in loops are deprecated
    75. Warning: String.x is deprecated; use String.prototype.x instead
    76. Warning: expression closures are deprecated
    77. Warning: unreachable code after return statement
  13. 杂项
    1. JavaScript 技术概述
    2. 词法语法
    3. JavaScript 数据结构
    4. Enumerability and ownership of properties
    5. Iteration protocols
    6. 严格模式
    7. 过渡到严格模式
    8. 模板文字
    9. 弃用特征