1月 14, 2020 Javascript
很多時我們也會在程式用上 Random String,用來作為暫時的 ID 或者用來生產 TOKEN。

### TL;DR

我們可以使用隨機數字來生產隨機的字串。以下 Script 可以產生 8 個位的隨機字串 :

```js
// create random string
Math.random().toString(36).slice(2, 10);
```

### 原理

以上的 Script 其實是把使用 `Math.ramdom()` 生產出來的隨機數字變成 36 進位的字串。由此推理出,也可以生成其他進位的字串 :

```js
// hexadecimal
Math.random().toString(16).slice(2);

// octadecimal
Math.random().toString(8).slice(2);

// binary
Math.random().toString(2).slice(2);
```

### 實作

不過以上都只可以當作為快速用途,生成的字符都是在 a-z 及 0-9 之間,如果要加入更多的字符,就要用較為複雜的邏輯了。

```js
/**
 * generate random string
 */
function randStr(length) {

	// result container
	var result = [];

	// characters pool
	var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';

	// create random string
	for (var i = 0; i < length; i++) {

		// get random position character
		result.push(chars.charAt(Math.floor(Math.random() * chars.length)));
	}

	// return result
	return result.join('');
}

// print random string with 8 characters
console.log(randStr(8));
```

> 參考資料 : https://stackoverflow.com/questions/1349404/generate-random-string-characters-in-javascript
過去文章
2025 (9)
4 (5)
3 (1)
2 (3)
2024 (25)
11 (3)
10 (3)
9 (1)
3 (18)
2022 (6)
10 (1)
6 (2)
5 (1)
3 (1)
1 (1)
2021 (21)
11 (7)
7 (1)
6 (2)
5 (2)
4 (6)
3 (2)
2 (1)
2020 (92)
12 (1)
11 (2)
10 (4)
9 (10)
8 (5)
7 (1)
6 (3)
5 (1)
4 (4)
3 (25)
2 (7)
1 (29)
2019 (57)
12 (25)
11 (7)
9 (25)