1

I have this function :

function hasNumber(word) { return /^[A-Za-z]+$/.test(word) } console.log(hasNumber('some text')); //true console.log(hasNumber('some text2')); //true 

but it always returns true Can somebody explain me why?

4
  • did you checked this link, stackoverflow.com/questions/10003683/… Commented Nov 27, 2014 at 20:41
  • you are looking for letters. the ^ here is the start of the string and not the negation operator. Commented Nov 27, 2014 at 20:47
  • 2
    The examples you give both return false when I try it. jsfiddle.net/zbxvpo72 Commented Nov 27, 2014 at 20:50
  • It seems like you used the expression from here. Make sure to also read the question properly. Commented Nov 27, 2014 at 21:11

1 Answer 1

3
function hasNumber( str ){ return /\d/.test( str ); } 

results:

hasNumber(0) // true hasNumber("0") // true hasNumber(2) // true hasNumber("aba") // false hasNumber("a2a") // true 


While the above will return truthy as soon the function encounters one Number \d
if you want to be able return an Array of the matched results:

function hasNumber( str ){ return str.match( /\d+/g ); } 

results:

hasNumber( "11a2 b3 c" ); // ["11", "2", "3"] hasNumber( "abc" ); // null if( hasNumber( "a2" ) ) // "truthy statement" 

where + in /\d+/g is to match one or more Numbers (therefore the "11" in the above result) and the g Global RegExp flag is to continue iterating till the end of the passed string.

Advanced_Searching_With_Flags
RegExp.prototype.test()
String.prototype.match()

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

1 Comment

@FelixKling exactly, we're looking for just a single number in order to be truthy therefore the + or more iterator is not needed.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.