javascript - String to regex
问题描述
I save in my database an String with a regex to validate one field, so when I bring from my back the regex to validate he comes with String type, so how can I convert that regex in a string to a regex to use with .test
So how I transform this:
"/^([a-z0-9]{5,})$/".test('12345');
Into this:
/^([a-z0-9]{5,})$/.test('12345');
tks
解决方案
RegExp构造函数接受一个字符串,它将解析为正则表达式。
const pattern = "^([a-z0-9]{5,})$";
const regex = new RegExp(pattern);
regex.test("...")
/regex/ 基本上只是 new RegExp("regex") 的语法糖
推荐阅读
- javascript - 在 Lodash 中按条件合并两个 JSON 数组
- javascript - 如何使用演示应用程序创建 npm 包?
- github-api - GitHub Licenses API 返回有限集
- sql - 无法绑定多部分标识符“company.ID”
- javascript - Leaflet-easyprint - 标记标签文本缩小
- time - 在 2038 年后保持兼容
- logic - 线性时序逻辑等价
- reactjs - Redux-Promise 不起作用
- javascript - 如何在反应组件中导入图表专家?
- sql-server - 如何从链接服务器查看 SQL Server 存储过程?