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

可能重复:
你如何将一个变量传递给正则表达式JavaScript?

我需要帮助来解决问题,因为代码由于numLength [0]而失败:

<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);
}
</script>

</body>
</html>

任何帮助将不胜感激。


使用RegExp constructor,如:

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

要么:

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

尝试这个:

<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);
}
</script>

numLength [0]是5.我们不能在正则表达式中添加变量的评估。 下面的代码返回true。

var result = /^[-+]?d{0,x}(.d{0,5})?$/.test(number);
链接地址: http://www.djcxy.com/p/76827.html

上一篇: how to pass a variable into an regular expression in javascript

下一篇: How to use a variable inside a RegEx pattern?