mario
mario

Reputation: 624

JS. How do I create a regex pattern by concatenation with variables

I am not able to fix the following:

<html>
<head>
    <title>Test</title>

<script>
   function myFunction(arr) {
     var N = [0,1,2,3,4,5,6,7,8,9];
     for (var s in N) {

     var pattern = new RegExp('/^[A-z]et_[' + s + ']_\\d/');
     // NOTE I get the following, is that how it should be?
     // window.alert(pattern);  =>  /\/^[A-z]et_[0]_\d\//
     // NOTE: I checked that it works fine for a single digit case, say:
     // var pattern = new RegExp(/^[A-z]et_[3]_\d/);  
    var newarr = arr.filter(elt => pattern.test(elt));
    document.getElementById("demo").innerHTML = newarr;
    }}
</script>

</head>
<body>
<div id="demo" onclick="myFunction(['aaaLet_0_0', 'Let_1_99', 'Let_2_',   'Let_3_99', 'Pet_2_', 'Pet_3_99', '_9_33']);">click here</div>
<hr>
<p>expected output: Let_1_99, Let_3_99, Pet_3_99</p>
</body>
</html>

I see many similar questions, but I have not been able to find out how to fix my code. It should be possible, shouldn't it?

EDIT the following is what I need:

 <html>
 <head>
 <title>Test</title>
 <script>

 var newarr = [];
function myFunction(arr) {
    var N = [0,1,2,3,4,5,6,7,8,9];
    for (var s in N) {

    var pattern = new RegExp('^[A-z]et_' + s + '_\\d'); // NOTE: not /
    var lnewarr = arr.filter(elt => pattern.test(elt));
    if(typeof lnewarr !== 'undefined' && lnewarr.length > 0){newarr.push(lnewarr)};
    }
    document.getElementById("demo").innerHTML = newarr;
    }
   </script>

  </head>
  <body>
  <div id="demo" onclick="myFunction(['aaaLet_0_0', 'Let_1_99', 'Let_2_', 'Let_3_99', 'Pet_2_', 'Pet_3_99', '_9_33']);">click here</div>
  <hr>
  <p>expected output: Let_1_99, Let_3_99, Pet_3_99</p>
  </body>
  </html>

(sorry if my post is mostly code. Hope it may helps somebody out there.)

Upvotes: 1

Views: 97

Answers (1)

anubhava
anubhava

Reputation: 784958

Instead of for loop you can use a .join like this:

var pattern = new RegExp('^[A-Za-z]et_[' + N.join('') + ']_\\d');
//=> /^[A-Za-z]et_[0123456789]_\d/

This works for the case when you have singe character values in your array N.

For generic use you can use this expression:

var pattern = new RegExp('^[A-Za-z]et_(?:' + N.join('|') + ')_\\d');
//=> /^[A-Za-z]et_(?:0|1|2|3|4|5|6|7|8|9)_\d/

Using a for loop you can do this:

var N = [0,1,2,3,4,5,6,7,8,9];
var str='(?:';
for (var s in N)
   str += s + '|';    
str = str.replace(/\|$/, ')');

var pattern = new RegExp('^[A-Za-z]et_' + str + '_\\d');
//=> /^[A-Za-z]et_(?:0|1|2|3|4|5|6|7|8|9)_\d/

Upvotes: 1

Related Questions