0

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.

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

3 Comments

can u please provide a sample for above?It would be really useful as i am new bibe to reg expression
@user1991222, Yeah. Give me second.
This is a fine explanation of how to create dynamic regexps, but it really should show how to do that in the context of the OP's question.
0

Why use regexp? Just check the number directly.

function make_decimal_validator(digitBeforeDec,digitAfterDec) {
    return function(no) {
        var parts = no.split('.');
        if (parts.length !== 2) throw "Invalid decimal number";
        return parts[0].length === digitBeforeDec && parts[1].length === digitAfterDec;
    };
}

Make your validator:

var validator23 = make_decimal_validator(2, 3);
validator23('12.345') // true

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.