Javascript - Insert A Variable Into Regexp
Solution 1:
There are several things wrong in your code.
RegExpexpects a string, not a regex literal like you pass in the first case. It seems thatRegExpis 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 toRegExp, 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 wordhello, it matches eitherh,e,loro, thus it is equivalent to[ehlo].
With all that said, your code should be:
var i = "hello";
var re = newRegExp('^$|^'+i+'|^([FG]?\\d{5}|\\d{5}[AB])$');
Solution 2:
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 = newRegExp("^" + word + "\\s?")
console.log( str.match(re) );
Post a Comment for "Javascript - Insert A Variable Into Regexp"