1

I'm trying to check if there's a number in a text input using regular expression. Here's the code:

var regex = /^[0-9]+$/;
if (myInput.val().match(regex)) {
    console.log("number");
} else {
    console.log("bad");
}

It works well, but if I add text, then backspace all the way, I get "bad". How can I make it log "good" when there isn't anything in the text input? I don't want to allow spaces, but I want to allow an empty input.

I tried:

var regex = /\s ^[0-9]+$/;

But then whatever I insert in the input, I always get "bad".

11
  • 2
    Try /^[0-9]*$/ and use RegExp#test instead of String#match Commented Dec 8, 2015 at 5:46
  • Why not just do two checks? if (!val.length || val.match(regex)) Commented Dec 8, 2015 at 5:48
  • @Tushar Can you explain about the RegExp#test and explain why it's better than what I have? Commented Dec 8, 2015 at 5:51
  • @epascarello I thought of that, but then what's the point of doing 2 checks when I can just do 1. Commented Dec 8, 2015 at 5:52
  • You said " if there's a number in a text". Do you mean you want to match positive on 1234, as well as on a1a,1ab12 and abd1? Not only on text which contains only numbers, but on number/letter as well? Commented Dec 8, 2015 at 6:09

2 Answers 2

5

This might fit , either you test for your Exp (^[a-zA-Z0-9]+$) or for an empty string (^$).

var regex = /(^$)|(^[a-zA-Z0-9]+$)/;
if (myInput.val().match(regex)) {
    console.log("number");
} else {
    console.log("bad");
}
Sign up to request clarification or add additional context in comments.

4 Comments

How does your answer differ from @gurvinder372's answer? Which one is recommended, and why?
In my RegEx I am trying first to check for an empty string, if this is not the case, i am checking for digits. Basically the same as gurvinder, but on the one hand i never feel comfortable with the * operator, on the other hand it might run faster, if you check for an empty string first, and only using the "bigger" one afterwards. Also, did you read my comment in your OP?
Is it bad to use * ?
imho greedy Operators are never a good thing. But since i am using +.. well, I did not say my solution was perfect. But since * catches even more than +, i tend to use it as less as possible.
1

try this (* in place of +)

var regex = /^[0-9]*$/;
if (myInput.val().test(regex)) {
    console.log("number");
} else {
    console.log("bad");
}

Comments

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.