Use variable inside the regular expression in javascript

This question already has an answer here:

  • How do you use a variable in a regular expression? 16 answers

  • 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.

    链接地址: http://www.djcxy.com/p/76834.html

    上一篇: 正则表达式中的变量

    下一篇: 在javascript中使用正则表达式中的变量