1

I have an array with the following regular expression strings.

var fieldTypes = [
{
    '/^[0-9]+$/',
    '/^(true|false)$/i',
    '/^\\d{4}-\\d{2}-\\d{2}$/',
    '/^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}$/i',
    'yyyy-mm-ddThh:mm',
];

Now how can I test whether a string matches one of them?

I'm trying something like this.

var value = 'some string';
if (!value.test(fieldTypes[0])) {
    alert('The value is not in the correct format.');
    return;
}

But this produces an error that test() is not a function. Obviously, it can't be called on a string directly. But how do I get a valid regular expression object from a string?

UPDATE:

The suggested answer is completely different. Please read the question before closing it. I have strings. They are coming from another source. It cannot be changed. I quite clearly asked how I can get a valid regular expression from a string. If there's no way, then that's the answer. But telling me to use a regular expression literal is not an answer.

Jonathan Wood
  • 65,341
  • 71
  • 269
  • 466
  • 1
    You can do it [like **this js demo** at tio.run](https://tio.run/##ZU5BDoIwELzzij2YAJGCIAeVwM0fcFNMGroIpljSItEob8cKGA9uNpPMzs5kLrSjKpdV05JuMwwdlVBUyFn6aFBBDAcDwDsdVmSbLReeMzKrlTd8FZQrtBdeNR2P7Bn2RGMw4/f7T0hH3M1Pk/2hh9Q1YSwty11da28WGcanTkf5DXUT0w/WIfEDvaaWfi3dQsg9zUtL4hnvECfw1JG5uCrB0eXiPAkOmHFigjMSt0XVWmO0bUdGb0fD8AY) Notice that it's `regex.test(value)` and not vice versa, further in the array remove the single quotes and additional backslashes to use the items as regex patterns. – bobble bubble May 16 '23 at 18:45
  • @bobblebubble: Thanks! I'm not sure I completely understand that. (I'm primarily a C/C# programmer.) Where does the `regex` come from in the `forEach()`? It looks like it's just my string, so how is it different from what I was doing? – Jonathan Wood May 16 '23 at 18:48
  • 1
    It's just a [JS forEach loop](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach?retiredLocale=de). Works like `array.forEach(element => { /* do something */ });` – bobble bubble May 16 '23 at 18:50
  • 1
    @bobblebubble: Oh, I see now. They aren't strings, they are regular expression literals. – Jonathan Wood May 16 '23 at 18:54

1 Answers1

3

If you can't modify the array, you likely need to parse the strings and generate regex objects.

For parsing purposes use some simple pattern like: ^(?:\/(.*)\/([a-z]*)|.*)$

It contains two options: The left side of the alternation \/(.*)\/([a-z]*) will capture the pattern part into the first group and any flags like i to a second group. The right side .* matches anything else if no delimiters were found (if left side failed). Finally construct the regexes using new RegExp.

Further notice that the order is regex.test(value) and not vice versa (easily confused with match).

var fieldTypes = [
  '/^[0-9]+$/',
  '/^(true|false)$/i',   
  '/^\\d{4}-\\d{2}-\\d{2}$/',
  '/^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}$/i',
  'yyyy-mm-ddThh:mm'
];

var value = '2000-01-01';

// parse string to regex
function strToRegex(s)
{
  let m = s.match(/^(?:\/(.*)\/([a-z]*)|.*)$/);
  if(m[1])
    return new RegExp(m[1], m[2]); // delimiters
  return new RegExp(m[0]); // no delimiters
}

// test value against regex
fieldTypes.forEach(regex_str =>
{
  let regex = strToRegex(regex_str);
  console.log(regex, '=>', regex.test(value));
});
bobble bubble
  • 16,888
  • 3
  • 27
  • 46