4

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.

0

3 Answers 3

5

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Exactly. Regular expression literals can't be concatenated with string literals.
0

try this:

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

Comments

-1

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);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.