# encodeURI VS. encodeURIComponent
共同點是因為在 `web` 中的 `url` `encode ` 採用的是 `ASCII` 格式,這邊先不理會 `ASCII` 是什麼,只要先理解他是一個 `url string` 的標準,通常如果單純打英文字母不會需要太在意這件事,但如果你的 `url` 中包含 `中文` 、`emoji`,或是其他`跳脫字元 ( escape string )`例如 `|`
,這時 `URL` 可能不會理解你的字元內容,所以才會需要 `encodeURI` 跟 `encodeURIComponent` 來做使用。
## encodeURI
`encodeURI` 常用於轉譯除 `URL` 字元以外的其餘字元,聽起來很難理解沒關係我們上範例。
`補充字元 分類`
#### URL 字元
```typescript
"/", "?", "&", "=", ";", ",", "@", "#", "+","$"
```
#### 語意字元 (簡單條列)
```typescript
a-z, A-Z, 0-9 ,(),[],{},!,~,*
```
### 什麼是 URL 字元
仔細看下面這 `URL`
`https://www.google.com/?redirectUrl=https://www.youtube.com/`
` URL 字元` 白話來說就是會用在 `URL` 上的特殊符號例如 `:` 、 `?` 、`/` 等等
所以如果你是放正常的 `url` `encode` 結果是不一樣的
```typescript
const input = `https://www.google.com/?redirectUrl=https://www.youtube.com/`
encodeURI(input) // https://www.google.com/?redirectUrl=https://www.youtube.com/
```
那這時候問題就來了那如果都沒變化我們要用 `encodeURI` 幹嘛?沒事我都知道,一開始有說 `encodeURI` 他只 `encode` 除了 `URL` 字元以外得特殊符號,所以如果 `url` 中沒有包含 `URL 字元` 的其他符號就會被 `encode`,例如以下範例。
### emoji
```typescript
const input = `https://www.google.com/emoji=😄`
encodeURI(input) // https://www.google.com/emoji=%F0%9F%98%84
```
### 中文
```typescript
const input = `https://www.google.com/string=中文`
encodeURI(input) // https://www.google.com/string=%E4%B8%AD%E6%96%87
```
### escape string
```typescript
const input = `https://www.google.com/escape=|`
encodeURI(input) // https://www.google.com/escape=%7C
```
#### 小節 encodeURI
正常情況如果只需要單純 `encode` `URL` 的話就用 `encodeURI` 就夠,那為什麼我們會需要 `encodeURIComponent` 呢?我們繼續說下去。
## encodeURIComponent
上面的 `encodeURI` 有說到除了 `url 字元外` 其餘字元都會被 `encode`
```typescript
const input = `https://www.google.com`
encodeURI(input) // https://www.google.com/https//www.youtube.com/
encodeURIComponent(input) // https%3A%2F%2Fwww.google.com
```
`encodeURI` 會原封不動地返回一樣的內容,但`encodeURIComponent` 卻可以 `encode` 所有字元的部分。
這時你會發現很有趣的現象 `encodeURIComponent` 的結果是無法造訪的 `url` ,所以使用上我們並不會透過 `encodeURIComponent` 去 `encode` 整個 `URL`。

取而代之的是我們會用來 `encode` `query string` 如下,如果我們可以確保 `data` 不管是 `中文` 或是 `emoji` 都可以成功 `encode` ,同時 `url` 也可以使用。
```typescript
<Link href={`/edit?data=${encodeURIComponent(data)}`}>
<div className="flex items-center gap-5">
<EditIcon />
<span>edit</span>
</div>
</Link>
```
### 額外使用
當我們想計算`string` 假如包含 `emoji` 或其他字元的總長度時,`encodeURIComponent` 可以幫我們計算長度。
```typescript
const strlength = encodeURIComponent(value).length
```