一、String对象是对原始string类型的封装。

  1. const foo = new String('foo'); // 创建一个String对象
  2. console.log(foo); // 输出: [String: 'foo']
  3. typeof foo; // 返回'object'

二、可以在String字面量上使用String对象的任何方法。
1、JavaScript自动把String字面量转换为一个临时的String对象,然后调用其相应方法,最后丢弃此临时对象。2、在String字面值上也可以使用String.length属性。
三、尽量使用String字面值,因为String对象的某些行为可能并不与直觉一致。
【实例1】

  1. const firstString = '2 + 2' // 创建一个字符串字面量
  2. const secondString = new String('2 + 2') // 创建一个字符串对象
  3. eval(firstString) // 返回数字4
  4. eval(secondString) // 返回字符串’2 + 2‘

String对象的属性

属性 描述
length 标识了字符串中UTF-16的码点个数

length

一、字符串长度
【示例1】

  1. alert( `My\n`.length ); // 3

1、注意\n是一个单独的“特殊”字符,所以长度确实是3。
二、可以通过数组的方式访问每一个码点,但是不能修改每个字符,因为字符串是不变的类数组对象。
【示例1】下面的代码把13赋值给了helloLength,因为’Hello, World!”包含13个字符,每个字符用一个UTF-16码点表示。

  1. const hello = 'Hello World'
  2. const helloLength = hello.length;
  3. hello[0] = 'L' // 无效,因为字符串是不变的
  4. hello[0] // 返回'H'

字符串是不可变的

一、在 JavaScript 中,字符串不可更改。改变字符是不可能的。
二、我们证明一下为什么不可能:

  1. let str = 'Hi';
  2. str[0] = 'h'; // error
  3. alert( str[0] ); // 无法运行

三、通常的解决方法是创建一个新的字符串,并将其分配给str而不是以前的字符串。

  1. let str = 'Hi';
  2. str = 'h' + str[1]; // 替换字符串
  3. alert( str ); // hi

String对象的方法

【见】String对象的方法:https://www.yuque.com/tqpuuk/yrrefz/egg67v