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?

Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313
Silver Jay
  • 556
  • 1
  • 4
  • 11
  • did you checked this link, http://stackoverflow.com/questions/10003683/javascript-get-number-from-string – mwafi Nov 27 '14 at 20:41
  • you are looking for letters. the ^ here is the start of the string and not the negation operator. – Octopus Nov 27 '14 at 20:47
  • 2
    The examples you give both return false when I try it. http://jsfiddle.net/zbxvpo72/ – Stuart Nov 27 '14 at 20:50
  • It seems like you used the expression from [here](http://stackoverflow.com/a/5778085/218196). Make sure to also read the question properly. – Felix Kling Nov 27 '14 at 21:11

1 Answers1

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()

Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313
  • @FelixKling exactly, we're looking for just a single number in order to be `truthy` therefore the `+` *or more* iterator is not needed. – Roko C. Buljan Nov 27 '14 at 21:18