0

Basically I need to use variables in a RegExp situation
I am aware that there is tutorials on google about this topic and posts about this on

this site but those sources are hard to understand to me personally so I have this script that I made basically I want to add custom number ranges as variables
between RegExp characters, I have tried suggested methods like new RegExp() but I

don't know how I can integrate what I want into that. So if any one can give me a code example with or with out new RegExp or another working method to make this happen I will really appreciate that. Here is my code

<script>
document.addEventListener('DOMContentLoaded', function(){
  
 document.getElementById('check').addEventListener('click', customRange);
  
 function customRange() {
   
   //Custom range numbers
   var startingNumber= document.getElementById('starting-number').value;
   var endingNumber= document.getElementById('ending-number').value;
   //
   
    var string = 'Is this all there is 123456789?';
   
   /*Example
   var pattern = /[2-5]/ig; 
   */

/*My attempt
   var pattern = /[startingNumber-endingNumber]/ig; 
  */
   
var result = string.match(pattern);
   alert(result);
   
}
  
});
</script>

<input id='starting-number' type='text' placeholder='Starting number'>
<input id='ending-number' type='text' placeholder='Ending number'>
<button id='check'>Check</button>

1 Answers1

1

You are right, new RegExp() is what you are looking for. For example:

var pattern = new RegExp('[' + startingNumber + '-' + endingNumber + ']', 'ig');
MatthewG
  • 8,583
  • 2
  • 25
  • 27
  • Thank you so much @MatthewG I now understand this now thanks to you. You are a great teacher. –  May 07 '18 at 00:25