# 1.8.1 String 里的方法

## 1. `toLowerCase()` 和 `toUpperCase()`

### 1.1 原理

1. UniCode 编码
2. 两个方法
   * `str.charCodeAt(index)` 取单个字符，得到它的编码
   * `String.fromCharCode(num)` 将编码转换成字符

<figure><img src="/files/b7g4UgRulu5xTqpsN5KE" alt=""><figcaption><p>16 bits 是 two bytes</p></figcaption></figure>

上图是基础拉丁语，范围是 `0000−007F`，共 128 个字符。

### 1.2 实现

```javascript
function to(str, min, max, dist){
    let arr = str.split('');
    for(let i in arr){
        let cur = arr[i].charCodeAt();
        if(cur >= min && cur <= max) arr[i] = String.fromCharCode(cur + dist);
    }
    return arr.join('');
}

const toLowerCase = function(str){
    const A = 'A'.charCodeAt();
    const Z = 'Z'.charCodeAt();
    return to(str, A, Z, 32);
}
const toUpperCase = function(str){
    const a = 'a'.charCodeAt();
    const z = 'z'.charCodeAt();
    return to(str, a, z, -32);
}
```

### 1.3 扩展阅读

* <https://anjia1.gitbook.io/cs-foundation/string/unicode>
* <https://unicode-table.com/en/>
* <https://unicode-table.com/en/blocks/basic-latin/>

## 2. 用下标取单字符信息

### 2.1 `charAt(i)` vs `[i]`

不同点：

1. 兼容性
   1. `charAt()` ECMAScript 3，IE7 和 IE6 也支持
   2. `[]` ECMAScript 5，IE7 和 IE6 不支持
2. 边界不同
   * 非数值类型，是否进行类型转换
   * 超过有效范围时

![](/files/aimpg0l3B9xhgQMbRBmn)

<https://stackoverflow.com/questions/5943726/string-charatx-or-stringx>

### 2.2 `charAt(i)` vs `at(i)`

都返回字符（串），由指定位置的 the single UTF-16 code unit 组成的。

不同点：下标

1. `str.charAt(i)` 下标范围 `[0, str.length-1]`，且会自动进行 Number 类型转换
2. `str.at(i)` 下标支持负数

### 2.3 `charCodeAt()` vs `codePointAt(i)`

不同点：对于值大于 `0xFFFF` 的 code point，它不能被单个 UTF-16 code unit 表示

1. `str.charCodeAt(i)`，
   * 返回整数，范围在 `[0, 65535]`，表示指定位置的 UTF-16 code unit
   * 注意：如果 Unicode code point 不，那么此方法只会返回 code point 的一部分（比如 ）如果想要整个 code point 的值，可以使用 `codePointAt()`
2. `str.codePointAt(i)` &#x20;


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://anjia1.gitbook.io/web/js/data-type/detail/string-method.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
