如何在javascript中将变量传递给正则表达式

how to pass a variable into an regular expression in javascript

本问题已经有最佳答案,请猛点这里访问。

Possible Duplicate:
How do you pass a variable to a Regular Expression JavaScript?

我需要帮助解决这个问题,因为代码失败,因为NuMnLe[ 0 ]:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<html>
<body>

<script type="text/javascript">
function xyz(){
var predefLength ="5,5";
var number ="20";
var numLength = predefLength.split(",");
var result = /^[-+]?\d{0,numLength[0]}(\.\d{0,numLength[1]})?$/.test(number);
document.write(result);
}


</body>
</html>

任何帮助都将不胜感激。


使用RegExp构造函数,例如:

1
var pattern = new RegExp('pattern as a string', 'flags as a string');

或:

1
var result = new RegExp('^[-+]?\d{0,' + numLength[0] + '}(\.\d{0,' + numLength[1] + '})?$').test(number);


试试这个:

1
2
3
4
5
6
7
8
9
10
<script type="text/javascript">
function xyz(){
var predefLength ="5,5";
var number ="20";
var numLength = predefLength.split(",");

var pattern = new RegExp('^[-+]?\\d{0,'+numLength[0]+'}(\\.\\d{0,'+numLength[1]+'})?$');
var result = pattern.test(number);
document.write(result);
}


numlength[0]为5。不能在正则表达式中添加变量的计算。下面的代码返回true。

1
var result = /^[-+]?\d{0,x}(\.\d{0,5})?$/.test(number);