0

I know this question already has an answer. I have read this [answer][1]. But it doesn't work for me. Since I am new to regEx and js, I didn't understand why they use these kinds of code like below for passing parameter.

var replace = "regex";
var re = new RegExp(replace,"g");

I have attached my code which I wrote in JSP. I used bootstrap validator. Please find it below

/* Get the domain name from the controller */ 

var domainName = ${domainName}

                  /*Validation part*/  
         email: {
                    trigger: 'blur',
                    validators: {
                        notEmpty: {
                            message: 'The email address is required'
                        },
                        regexp: {
                            regexp : /"^([\w-\.]+)@" + domainName/,
                            message: 'The domain name is wrong and your domain name is: ' + domainName
                        }
                    }
                }

Here I have written regexp as /"^([\w-.]+)@" + domainName/. In message I have written the variable name as domainName. So the message has been shown in the GUI. I need to know how to pass the variable (domainName) to regEx. Please explain how to do that?

EDIT 1: If I hardcode regEx like this, it works. But hardcoding is not great idea.

           regexp : /^([\w-\.]+)@(example.com|example1.com|uk.co|gmail.com)$/,

ANSWER: I solved this issue. Once I got the domain name, I have divided the regex and domain name in separate variables and concatenated them in variable(pattern).

    var domainName = ${domainName}

        const pattern1 = String.raw`([\w-\.]+)`;
        const pattern2 = (domainName);
        const pattern = new RegExp("^" + pattern1 + "@" + pattern2 + "$");

I have mentioned the variable "pattern" in validation part and its worked successfully.

                email: {
                    trigger: 'blur',
                    validators: {
                        notEmpty: {
                            message: 'The email address is required and cannot be empty'
                        },
                        regexp: {
                            regexp : pattern,
                            message: 'The domain name is wrong and your domain name is: ' + domainName

                        }

                    }
                },

  [1]: https://stackoverflow.com/questions/494035/how-do-you-use-a-variable-in-a-regular-expression
Satheeshkumar
  • 55
  • 2
  • 9

2 Answers2

1

You can use the Regex contractor that accepts string.

const regex = new RegExp('"^([\w-.]+)@"' + domainName);

EDIT

Change this line:

regexp : /"^([\w-\.]+)@" + domainName/,

to:

regexp : new RegExp('"^([\w-.]+)@"' + domainName),
felixmosh
  • 20,379
  • 4
  • 36
  • 56
0

You can try this JavaScript automatically adds "/" at the end and the beginning of the expression. So you can ignore them.

 var expression = "^([\w-\.]+)@ + domainName" ;

Srimoyee Sen
  • 173
  • 9