2
function checkEmail(str){ var emailCheck = /[^a-z][0-9]/; if(emailCheck.test(str)){ console.log("**Its Valid Mail"); } else{ console.log("Its not Valid"); } } var x = '122a'; checkEmail(x); 

I have been learning Regular Expressions. From the above code what I understand, x should not contain small a-z and it must contain number, as you can see 122a contains number as well as small letter a, I think it should be invalid but yet I get it as valid. Can anyone please explain where I am thinking wrong.

3 Answers 3

6

The problem is, you are not checking the start and end of the string.

Specify the Start and End of your Regex:

/^[^a-z][0-9]+$/ 

The caret ^ and dollar $ characters have special meaning in a regexp. They are called anchors. The caret ^ matches at the beginning of the text, and the dollar $ – in the end.

function checkEmail(str){ var emailCheck = /^[^a-z][0-9]+$/; if(emailCheck.test(str)){ console.log("**Its Valid Mail"); } else{ console.log("Its not Valid"); } } var x = '122a'; checkEmail(x);

For more: Start of String and End of String Anchors in Regular Expression

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

Comments

1

Try /^[0-9]+$/g.test(str).

> var s = '122a' undefined > > /^[0-9]+$/g.test(s) false > > var s = '122' undefined > > /^[0-9]+$/g.test(s) true > 

Comments

0

You regex [^a-z][0-9] matches 2 characters. The first would match not a-z using a negated character class and the second will match a digit. That will match 12 in 122a

The method test searches for a match in a string, finds a match 12 and will return true.

You could use anchors to assert the start ^ and the end $ of the string to match 2 characters. In that case, 122a will not match because that are 4 characters.

If you want to check if the string does not contain a lowercase character and does contain a digit you could use a lookahead to assert that what followes is not [a-z] and that what follows is digit [0-9].

^(?!.*[a-z])(?=.*[0-9]).*$

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.