How to create Dynamic Regular Expression in javascript to validate the decimal number

advertisements

I have to validate a decimal number based on the digits provided before the decimal and after the decimal. Say i have a function which is having a regular expression and takes two parameters as digits before the decimal and digits after the decimal.

function validateDecimalNo(digitBeforeDec,digitAfterDec){
          //here i need to write the regular expression to validate the  decimal no based on the inputs.
            }

  • If i pass 2,3 it should check decimal no as per this restriction
  • If i pass 10,6 it should validate no as per this restriction
  • If i pass 4,2 it should validate no as per this restriction

How to create the single dynamic regular expression to meet above requirement.


In JavaScript, you have literal syntax (/regex/, {object}, or even "string"), and you have the non-literal syntax (new RegExp(), new Object(), new String()).

With this provided, you can use the non-literal version of regex, which takes a string input:

var myRegex = new RegExp("hello", "i"); // -> /hello/i

So, this provided, we can make a function that creates a "dynamic regex" function (quotes because it's actually returning a new regex object every time it's run).

For instance:

var getRegex = function(startingSym, endingSym, optional){
  return new RegExp(startingSym + "(.+)" + endingSym, optional)
}

So, with this example function, we can use it like this:

var testing = getRegex("ab", "cd", "i");
console.log(testing);
// Output:
/ab(.+)cd/i