how to pass a variable into an regular expression in javascript

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

I need help to resolve the issue because the code fails due to 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>

Any help will appreciated.


Use the RegExp -constructor, like:

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

Or:

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] is 5. We can not add evaluation of variable in regular expression. Below code returns true.

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

上一篇: 如何使用正则表达式在Javascript中删除单个类?

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