JSON 本身是不支持正则表达式的,所以我们需要转换传递正则的方式。
# 方式 1
1. 假如有个正则表达式为
| // 字符长度为 1 到 16 之间 | |
| const regex = /^.{1, 15}$/ | 
2. 那么,JSON 格式可以写为
| { | |
| "regex": "^.{1, 15}$" | |
| } | 
3. 然后,解析时采用
| const regexp = new RegExp(regex) | |
| regexp.test('11111') | 
# 方式 2
1. 假如有个正则表达式为
| // 字符长度为 1 到 16 之间 | |
| const regex = /^.{1, 15}$/ | 
2. 获取正则的 source 与 flags
| const source = regex.source | |
| const flags = regex.flags | |
| const regexStr = JSON.stringfy({ source: source, flags: flags}) | 
3.JSON 传递
| { | |
| "regex": regexStr | |
| } | 
4. 解析
| const { source, flags } = JSON.parse(regex) | |
| const regexp = new RegExp(source, flags) | |
| regexp.test('11111') | 
