Reputation: 606
Recently I posted a question about time format conversion via regular expressions in JS.
Now I modified the code a bit.
function getHours(value) {
if (value == 0)
return 0;
var re = new RegExp("^(?=\d)((\d+)(h|:))?\s*((\d+)m?)?$", "g");
var myArray = re.exec(value);
var hours = 0;
var minutes = 0;
if (myArray != null) {
if (myArray[2] != null) {
hours = myArray[2];
}
if (myArray[5] != null) {
minutes = myArray[5];
}
}
return Number(hours) + Number(minutes) / 60;
}
The problem is that it returns a null
value in myArray
.
As I'm new to JS, I couldn't solve this problem. What am I doing wrong?
Upvotes: 1
Views: 995
Reputation: 7289
The problem is here
new RegExp("^(?=\d)((\d+)(h|:))?\s*((\d+)m?)?$", "g");
When you create a new Regular Expression through the constructor, you provide strings. In string literals, the backslash character (\
) means ‘escape the next character’.
You have to escape those backslashes, so they won't escape their subsequent character. So the correct version is:
new RegExp("^(?=\\d)((\\d+)(h|:))?\\s*((\\d+)m?)?$", "g");
See this article on values, variables, and literals from MDN for more information on escaping characters in JavaScript.
Upvotes: 2
Reputation: 785406
Problem is in this line:
var re = new RegExp("^(?=\d)((\d+)(h|:))?\s*((\d+)m?)?$", "g");
Pls understand that RegExp class
takes a String as argument to construct and you need to double escape \d
and \s
to be correctly interpreted by RegEx engine so \d
should become \\d
and \s
should become \\s
in your regex String like this:
var re = new RegExp("^(?=\\d)((\\d+)(h|:))?\\s*((\\d+)m?)?$", "g");
Note that you can also do:
var re = /^(?=\d)((\d+)(h|:))?\s*((\d+)m?)?$/g;
Upvotes: 1
Reputation: 606
I changed exec call like this:
var myArray = (/^(?=\d)((\d+)(h|:))?\s*((\d+)m?)?$/g).exec(value);
And it worked! Can anyone explain the difference?
Upvotes: 0