I have this JavaScript code:
let separator = '.';
let fee = '10.00';
let regex = new RegExp(/^[^a-zA-Z]*\.[^a-zA-Z]*$/);
console.log( regex.test( fee ) );
I want this to return false if the fee contains anything that isn’t a number and/or doesn’t contain the . separator.
- How can I make the regex use the string from the separator variable, rather than hardcoding it directly in the regex like I have currently
- How can I alter this regex to check for anything thats not a number and the separator, e.g. !@£$%^, currently it only does a-zA-Z
>Solution :
You can use the tick ` and then use a template literal expression: ${separator}.
- You must double escape values in a string regular expression.
- You no longer need to start/end the expression with
/ - Instead of testing for all characters using
[^a-zA-Z], test for digits using\d - we need to escape the separator as
.stands for anything.
let separator = '.';
let fee = '10.00';
let regex = new RegExp(`^\\d+\\${separator}\\d+$`);
console.log( regex.test( fee ) ); // True
console.log( regex.test( fee + 'abc' ) ); // False
console.log( regex.test( '1,23' ) ); // False
console.log( regex.test( '!@£$%^' ) ); // False
Here we change the separator to a comma, and now only the comma returns true:
let separator = ',';
let fee = '10.00';
let regex = new RegExp(`^\\d+\\${separator}\\d+$`);
console.log( regex.test( fee ) ); // False
console.log( regex.test( fee + 'abc' ) ); // False
console.log( regex.test( '1,23' ) ); // True
console.log( regex.test( '!@£$%^' ) ); // False
Note: if you need to have multiple separators in the same string, you could use the following:
`^\\d+[${separator}\\d]+\\d+$`