5

I have the following which works fine, allowing a form field to be valid if blank or containing the word "hello" or passing the other validation...

var re = new RegExp(/^$|^[hello]|^([FG]?\d{5}|\d{5}[AB])$/);

but I want to make the word "hello" be the value of a variable.

I have tried this but it no longer seems to work:

var i = "hello";
var re = new RegExp('/^$|^['+i+']|^([FG]?\d{5}|\d{5}[AB])$/');
4
  • Note that you're not checking for a string containing the word "hello" but rather it starting with the letters h,e,l or o. Commented Aug 14, 2012 at 14:34
  • This probably isn't your problem, but you also need to escape your ` \ ` characters when you write your regex as a string, e.g., \\d. Commented Aug 14, 2012 at 14:35
  • Your regexp also matches the word hyacinth. Commented Aug 14, 2012 at 14:36
  • Instead of including the ^ and $ in each option, you could just wrap the whole thing in parens: /^(|hello|[FG]?\d{5}|\d{5}[AB])$/. The fact that the [] around hello was doing the wrong thing has already been mentioned. Commented Aug 14, 2012 at 14:43

2 Answers 2

12

There are several things wrong in your code.

  • RegExp expects a string, not a regex literal like you pass in the first case. It seems that RegExp is smart enough though and detects that you are passing a regex literal. So your first example works by coincidence and is the same as:

    var re = /^$|^[hello]|^([FG]?\d{5}|\d{5}[AB])$/;
    
  • The / are not part of the expression, they are the delimiters to denote a regex literal, much like quotation marks (') indicate a string literal. Hence, if you pass the expression as string to RegExp, it should not contain /.

  • Since the backslash is the escape character in strings as well, in order to create a literal backslash for the expression you have to escape it: \\.

  • [hello] does not test for for the word hello, it matches either h, e, l or o, thus it is equivalent to [ehlo].

With all that said, your code should be:

var i = "hello";
var re = new RegExp('^$|^'+i+'|^([FG]?\\d{5}|\\d{5}[AB])$');
Sign up to request clarification or add additional context in comments.

Comments

3

Drop the leading and trailing / characters and your reg exp is not going what you expect. Double up the \ characters so they are escaped. Also [] means match any of these characters.

Basic example

var str = "hello world";
var word = "hello"
var re = new RegExp("^" + word + "\\s?")
console.log( str.match(re) );

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.