Matt
Matt

Reputation: 173

return number and word regex javascript

can someone tell me why my code keeps returning null, it used to return a match now its not and i dont know whats wrong. I want it to find a match in the string for 1 hour

var error = "null";

var str = "1 hour "


var strCheck = str.match(/[1]\s[hour]\s/g);

if(String(strCheck) != error) {
alert("works!");
}

Upvotes: 1

Views: 76

Answers (3)

Anand Singh
Anand Singh

Reputation: 2363

Check this..

var error = "null";

var str = "1 hour "


var strCheck = str.match(/1 hour /g);

if(strCheck != error) {
alert("works!");
}

Explanation:

[] is used to match a single character so [hour] is not correct and if you have change in number of hours you can make it like this:

var error = "null";

var str = "1 hour "


var strCheck = str.match(/[0-9][0-9] hour /g);

if(strCheck != error) {
alert("works!");
}

or Simply use \d to find a digit and \d+ to find one or more digit.
For more see this its simple and clear.

Upvotes: 2

DontVoteMeDown
DontVoteMeDown

Reputation: 21465

I don't know what kind of validation you need with that regex, but this can be useful:

\d+\s(hour(s)?)

Explanation:

  • \d+ One or more digits
  • \s A blank space
  • (hour(s)?) a string hour with optional s at the end for plural.

The match() method returns an array with the results or null if no match was found. So I suggest you simply check the result as a boolean instead of compare to "null" string. Then you code could be like this:

var strCheck = str.match(/\d+\s(hour(s)?)/, g);

if (strCheck) {
    alert("works!");
}

Some cases here.

Upvotes: 0

Vegeta
Vegeta

Reputation: 1317

The RegEx [1]\s[hour]\s will not work. The character class without quantifiers [] is used to match only a single character from the characters within it. So, [hour] will match one of the character from h, o, u and r. However, you want to match hour as complete string.

To make the regex more dynamic and match even 10 hours following regex can be used.

/\d+\s*hours?\s*/

Code:

var error = "null";
var str = "1 hour "
var strCheck = str.match(/\d+\s*hours?\s*/g);
if (strCheck != null) {
  alert("works!");
}

console.log(strCheck);

If you just want to check if the string contain a pattern, use RegExp#test instead of String#match.

/\d+\s*hours?\s*/.test(str)

Upvotes: 2

Related Questions