-2

I am trying to eject every results of an array that contain alphabetic characters. For this, I use :

if(gtin.toString().length != 13 || /[a-z\-]+/ig.test(gtin) == true) {
    gtin = "null";
}

It's works for some variable… But not every time. For exemple :

  • CS230
  • C1
  • L3940-noir

All of this variables will still appear on the array. Do you have an idea why this doesn't work ? Thank you !

tgogos
  • 23,218
  • 20
  • 96
  • 128
Sandra
  • 143
  • 2
  • 11

2 Answers2

1

You have to add digits and anchor your regex:

var test = [
    'abc',
    'CS230',
    'C1',
    'L3940-noir',
    'ab::cd'
];
console.log(test.map(function (a) {
  return a+' :'+/^[a-z0-9-]+$/ig.test(a);
}));
Toto
  • 89,455
  • 62
  • 89
  • 125
1

This really isn't an answer. It's more an illustration to that it does work.

var texts = ['CS230','C1', 'L3940-noir', '1231231231231', '/()!!!###&&&+', 'ABCDEFGHIJKLM', '0123456s78901'];

texts.forEach(function(gtin) {
          
  if(gtin.toString().length != 13 || /[a-z\-]+/ig.test(gtin) == true) {
    gtin = "null";
  }
  document.write(gtin + '<br/>');
});

Check this snippet and you'll see that all you're examples are set to null, i.e. "rejected" (which I guess is what you meant). It only lets strings that are 13 characters long, and without letters, through.

SamWhan
  • 8,296
  • 1
  • 18
  • 45