首页 > 解决方案 > 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

标签: javascriptregex

解决方案


RegExp构造函数接受一个字符串,它将解析为正则表达式。

const pattern = "^([a-z0-9]{5,})$";
const regex = new RegExp(pattern);
regex.test("...")

/regex/ 基本上只是 new RegExp("regex") 的语法糖


推荐阅读