-1

I know it's newbie question but i don't know how to get over with it.
Match() string using regex always returning false. Values are from autcomplete.

    var str = '1 - Hello';
    var pattern = /^[\d]\s-\s[a-z]/;
    if(str.match(pattern))
    {
        alert('Hell Yeah');
    }
    else
        alert('noooooooo');

I don't know what i am missing here. But in regex tester it's working.

My answer : /\d+ - \w+/i

Thanks for Responses. Voted for Close.

Insane Skull
  • 9,220
  • 9
  • 44
  • 63

2 Answers2

1

You're only allowing lower case letters, try:

var pattern = /^[\d]\s-\s[a-zA-Z]/;

This still only matches the first letter of 'Hello', if you want to match the whole word it'll be:

var pattern = /^[\d]\s-\s[a-zA-Z]+/;

MatCarey
  • 2,409
  • 1
  • 16
  • 12
  • Still not working. I don't care what is after `/^[\d]\s-\s[a-z]`. Pattern should be **number whitespace hyphen(-) whitespace characters**. – Insane Skull Mar 14 '16 at 13:19
  • @InsaneSkull Please clarify your question then - if you don't care what's after the `- `, why are you looking for `[a-z]`? – James Thorpe Mar 14 '16 at 13:21
  • `/\d\s-\s/` / `/^\d\s-\s/` should do the trick then? https://regex101.com/r/jT0mC9/1 (add ^ at the beginning if you only want matches at the start) – JakeSidSmith Mar 14 '16 at 13:26
1

Note the following change I have made based on the regex test you conducted.

var str = '1 - Hello'; 
var pattern = /^\d\s-\s[a-z]/i;
 //change made above
if(str.match(pattern)) 
{ 
alert('Hell Yeah'); 
} 
else 
alert('noooooooo');
Mathews Mathai
  • 1,707
  • 13
  • 31