可能重复:
How do you pass a variable to a Regular Expression 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>
任何帮助都会受到赞赏。
答案 0 :(得分:4)
使用RegExp
- 构造函数,例如:
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);
答案 1 :(得分:0)
试试这个:
<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>
答案 2 :(得分:-1)
numLength [0]是5.我们不能在正则表达式中添加变量的评估。下面的代码返回true。
var result = /^[-+]?\d{0,x}(\.\d{0,5})?$/.test(number);