Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use a variable in regex while checking for anything thats not a number or the variable

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.

  1. 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
  2. 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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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+$`
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading