nodejs利用string-random生成指定的隨機字符串


nodejs利用string-random生成指定的隨機字符串

 

nodejs提供的Math.random() 用於生成隨機數字,但是並未提供生成字符串的函數,要自己寫生成隨機字符串邏輯比較麻煩。string-random庫專門用於快速生成隨機字符串,並且可以根據需求制定字符串長度以及包含的字符。下面進行相關用戶的簡單介紹。

1.簡述

  1)random(length, options) 函數的第一個參數length為要生成的字符串長度,第二個參數是選項:

    - options 為true,生成包含字母、數字和特殊字符的字符串
    - options 為字符串,從options字符串中提供的字符生成隨機結果
    - options 為對象
  2)options 對象:

    - options.letters

    - true (默認) 允許大小寫字母
    - false 不允許大小寫字母
    - string 從提供的字符生成隨機結果


  3)options.numbers

    - true (默認) 允許數字
    - false 不允許數字
    - string 從提供的字符生成隨機結果

  4)options.specials

    - true 允許特殊字符
    - false (默認) 不允許特殊字符
    - string 從提供的字符生成隨機結果

2. 用法demo:

復制代碼
 1 const stringRandom = require('string-random');
 2 
 3 
 4 // 默認生成長度為8的字符串,包含大小寫字母和數字的隨機字符串
 5 console.log(stringRandom()); // oSjAbc02
 6 
 7 // 指定生成長度為16,包含大小寫字母和數字的隨機字符串
 8 console.log(stringRandom(16)); // d9oq0A3vooaDod8X
 9 
10 // 指定生成長度為16,僅包含指定字符的字符串
11 console.log(stringRandom(16, '01')); // 1001001001100101
12 
13 // 指定生成長度為16,包含大小寫字母的隨機字符串(不包含數字)
14 console.log(stringRandom(16, { numbers: false }));  // AgfPTKheCgMvwNqX
15 
16 // 指定生成長度為16,包含大小寫字母的隨機字符串(包含數字) 同console.log(stringRandom(16));
17 console.log(stringRandom(16, { numbers: true }));  // r48ZGVa7FsioSbse
18 
19 // 包含數字的隨機字符串(不包含字母) 默認是 true
20 console.log(stringRandom(16, { letters: false }));  // 0889014544916637
21 
22 // 包含制定字母和數字的隨機字符串
23 console.log(stringRandom(16, { letters: 'ABCDEFG' }));  // 055B1627E43GA7D8
24 
25 // 包含特殊字符 默認是false
26 console.log(stringRandom(16, { specials: true })); // ,o=8l{iay>AOegW[ 
27 console.log(stringRandom(16, true));             // SMm,EjETKMldIM/J
28 //包含指定特殊字符
29 console.log(stringRandom(16, { specials: "-" }));
復制代碼

 

@南非波波 github:https://github.com/swht
 
標簽: node
0
0
 
 
 
 
posted @ 2019-05-30 19:28  南非波波  閱讀( 1142)  評論( 0編輯  收藏


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM