Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to pass a variable into an regular expression in javascript [duplicate]

Tags:

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.

like image 844
Bidesi Avatar asked Oct 15 '25 16:10

Bidesi


1 Answers

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);
like image 89
Yoshi Avatar answered Oct 17 '25 06:10

Yoshi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!