I'm using JavaScript, I need to accept only string or string with comma-separated if there has more string.
My code is as follows
const text = 'AB1234567';
const hasText = text.match(/^([A-Za-z]{2}[0-9]{7}(,\s)?)+$/);
My code test is as follows
// first test
const text = 'AB1234567'; // output: 'AB1234567'
const hasText = text.match(/^([A-Za-z]{2}[0-9]{7}(,\s)?)+$/); // is good.
// second test
const text = 'AB1234567, '; // output: 'AB1234567, '
const hasText = text.match(/^([A-Za-z]{2}[0-9]{7}(,\s)?)+$/); // is good, but I dont need this.
// third test
const text = 'AB1234567, AB1234568'; // output: 'AB1234567, AB1234568'
const hasText = text.match(/^([A-Za-z]{2}[0-9]{7}(,\s)?)+$/); // is good, I need this.
// fourth test
const text = 'AB1234567, AB1234568, '; // output: 'AB1234567, AB1234568, '
const hasText = text.match(/^([A-Za-z]{2}[0-9]{7}(,\s)?)+$/); // is good, but I dont need this.
How can I accept only the correct value?
Correct values is first test and third test
Your regex will accept strings that end with a comma and a space, which apparently you don't want. So, let's make the regex enforce that the string doesn't end that way:
text.match(/^([A-Za-z]{2}[0-9]{7},\s)*[A-Za-z]{2}[0-9]{7}$/);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With