The regular expression pattern [1]\s[hour]\s
is not suitable for this task. The character class []
without quantifiers is designed to match only a single character from the specified characters. Therefore, [hour]
will match one of the characters - h
, o
, u
, or r
. If you want to match the word "hour" as a complete string, a different approach is needed.
To create a more dynamic regex pattern that can even match expressions like "10 hours," the 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 the goal is to simply check if the string contains a specific pattern, it's recommended to use RegExp#test
instead of String#match
.
/\d+\s*hours?\s*/.test(str)