Javascript regex should contain empty and non-empty string, but this is not

I have a regex that allows an empty string. If it is not empty, the string can only contain letters and spaces. But it cannot begin or end with a space.

This RegExp should do the job: ^(?! )[a-zA-Z]*[a-zA-Z ]*$ I tested it here: http://tools.netshiftmedia.com/regexlibrary/

But when I implement this in my js, it does not allow the string to be empty.

This is the code

 function validatePreposition(name) { string = string = document.forms['form'][name].value; pattern = new RegExp('^(?! )[a-zA-Z]*[a-zA-Z ]*$'); checkString(name, pattern, string); } function checkString(name, pattern, string) { if(!pattern.test(string)) { error[name] = 1; } else { error[name] = 0; } printErrors(); } 

How to change my code so that an empty string is allowed?

+4
source share
2 answers

Try using this instead:

 pattern = /(^[a-zA-Z]+(\s*[a-zA-Z]+)*$)|(^$)/; 

It will either check for an empty line, or it will check for a line that starts with aZ and can contain an unlimited number of spaces in the line, but must end with -Z.

You can see it in action here: http://jsfiddle.net/BAXya/

+14
source

You can also use this:

 if (subject.match(/^(?=[az ]*$)(?=\S)(?=.*\S$)/i)) { // Successful match } 

Use only lookaheads. Although I would go with @ Marcus's answer.

0
source

Source: https://habr.com/ru/post/1384063/


All Articles