0

I am trying to extract the GMT number from the following text:

All times are GMT -3. The time now is 07:00 PM. Archive

I have the code:

data = "All times are GMT -3. The time now is 07:00 PM. Archive";
var myregex = /s\GMT([^"]*)./;
var matchArray = myregex.exec(data);

But it doesn't seem to work. In this example I am trying to get "-3" into matchArray How can I get the string after the space after GMT and before the period? Thanks!

1
  • I guess you mean \s, not s\. There is no s in front of GMT in your input string, that's why /s\GMT doesn't match. Maybe it even tries to match \ literally, I don't know. Commented Aug 12, 2014 at 22:16

2 Answers 2

1

You need to use this regex:

var matchArray = /\bGMT *([^.]+)/.exec(data);
if (matchArray)
   console.log(matchArray[1]); //=> -3
Sign up to request clarification or add additional context in comments.

3 Comments

what happens if my time is -3.5? how can I make sure it will grab "-3.5"?
You can use: /\bGMT +(.+?)(?=\. )/.exec(data); for that input.
will that work for both -3 and -3.5? it's a variable so I don't know which number will be there
0

You can get it using this code:

var regex = /\bGMT\s+([-+][0-9]+)\b/;
var res = data.match(regex);

console.log(res[1]);

See JSFiddle.

Comments

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.