Use variable inside the regular expression in javascript
This question already has an answer here:
You should create a specific Regular Expression object to use with the .match()
function. This way you can create your regex with a string and insert the variable when creating it:
var changing_value = "put";
var re = new RegExp("bw*" + changing_value + "w*b", "ig");
Note that the ignore case ( i
) and global ( g
) modifiers are specified as the second parameter to the RegExp
constructor instead of part of the actual expression. Also that you need to escape the character inside the constructor because is also an escape character in strings.
Another thing to note is that you don't need the /
delimiters /
at the start and end of the expression when using the Regexp
constructor.
Now you can use the Regexp object in your call to .match()
:
string.match( re )
As a final note, I don't recommend that you use the name string
as a variable name... As you can see from the syntax highlighting, string
is a reserved word and it is not recommended to use names of built-in types for variable names as they may cause confusion.
上一篇: 正则表达式中的变量