1

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?

5
  • 1
    post the value of value variable too Commented Apr 26, 2013 at 10:22
  • it can be one of {"11h20m","11h","20","20m","11:20"} Commented Apr 26, 2013 at 10:25
  • What should (?=\d) do? There is x(?=y) which means matches x only if x is followed by y but then you miss the preceding value. Commented Apr 26, 2013 at 10:29
  • @zeroflagL that means that sting must start with digit Commented Apr 26, 2013 at 10:31
  • @StNickolas you already have \d+ (one ore more digits) as first value, so it already must start with a digit. Commented Apr 26, 2013 at 10:36

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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 \\sin 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;

Comments

0

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?

1 Comment

Wrong initialization, try: var re = new RegExp(/^(?=\d)((\d+)(h|:))?\s*((\d+)m?)?$/g). JavaScript string escapes "\" symbol, that is why you initialized completely different RegExp.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.