2

I have the following regular expression... This one does not allow empty String. How do I have to manipulate?

var phoneReg = new RegExp(/^\+?[0-9]+(\([0-9]+\))?[0-9-]*[0-9]$/i);

3 Answers 3

5

Just use the "zero or one" operator ?, such as:

/^(?:regex)?$/
           ^

(?:regex) simply makes the concerned ground uncapturable (i.e. no need to change your $X, \X or ?X indexes if any).

Sign up to request clarification or add additional context in comments.

Comments

3

I believe that the following would work:

/^$|^\+?[0-9]+(\([0-9]+\))?[0-9-]*[0-9]$/i

I've inserted ^$| at the beginning of your regex. The pipe (|) is called an "alternation" indicator and says that either the expression before it or after it must match. ^$ will simply match a string with no characters between the start and end of input. The result: an empty string or the original expression.

1 Comment

@user2286914 - Can you be more specific? Seems to work just fine here: regex101.com/r/cP2mD4
3

You can put a ^$| in front which in which ^ = beginning, $ = end, | = or this other thing to the right.

var phoneReg = new RegExp(/^$|^\+?[0-9]+(\([0-9]+\))?[0-9-]*[0-9]$/i);

1 Comment

@user2286914 - Visual Studio's interpretation of JavaScript is not of any particular importance (and is often wrong). Have you actually tried it in the browser?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.