-1
do{    
         var string1=prompt("Enter text");     
} while(!string1||!/^[a-zA-Z\s]*$/.test(string1));

Can someone please explain to me the condition inside while in detail?

Badrul
  • 1,582
  • 4
  • 16
  • 27

1 Answers1

2

!string will be true if the string is not empty, meaning string !== '' && string !== null && string !== false && string !== undefined

The regular expression /^[a-zA-Z\s]*$/ matches any string that only contains a letter/whitespace and by doing ! we want the oppossite. A string that contains at least one character that it is not a letter/whitespace

enter image description here

The .test method evaluates a regular expression against a given string, and will return true if the pattern matches the string.

So:

'333' // true
' 333' // true
'aaa' // false
'   ' // false
'3a3' // true

const arr = [
  '333', // I have at least 1 non letter/whitespace
  '444', // I have at least 1 non letter/whitespace
  ' 44', // I have at least 1 non letter/whitespace
  'a$', // I have at least 1 non letter/whitespace
  'aaaa', // false
  'ZZZ', // false
  '   ', // false
  '"$a%' // I have at least 1 non letter/whitespace
];

arr.forEach(string => {
  console.log(`${string}: ${!/^[a-zA-Z\s]*$/.test(string)}`);
});
Marcos Casagrande
  • 37,983
  • 8
  • 84
  • 98