For instance, I am using a simple regex to match everything before the first space:
var str = '14:00:00 GMT';
str.match(/(.*?)\s/)[0]; //Returns '14:00:00 ' note the space at the end
To avoid this I can do this:
str.match(/(.*?)\s/)[0].replace(' ', '');
But is there a better way? Can I just not include the space in the regex? Another examle is finding something between 2 characters. Say I want to find the 00 in the middle of the above string.
str.match(/:(.*?):/)[0]; //Returns :00: but I want 00
str.match(/:(.*?):/)[0].replace(':', ''); //Fixes it, but again...is there a better way?
For instance, I am using a simple regex to match everything before the first space:
var str = '14:00:00 GMT';
str.match(/(.*?)\s/)[0]; //Returns '14:00:00 ' note the space at the end
To avoid this I can do this:
str.match(/(.*?)\s/)[0].replace(' ', '');
But is there a better way? Can I just not include the space in the regex? Another examle is finding something between 2 characters. Say I want to find the 00 in the middle of the above string.
str.match(/:(.*?):/)[0]; //Returns :00: but I want 00
str.match(/:(.*?):/)[0].replace(':', ''); //Fixes it, but again...is there a better way?
Share
Improve this question
asked Sep 27, 2012 at 5:07
ryandlfryandlf
28.6k37 gold badges111 silver badges164 bronze badges
1
-
What's wrong with
str.split(' ')[0]
? – Blender Commented Sep 27, 2012 at 5:12
5 Answers
Reset to default 2I think you just need to change the index from 0 to 1 like this:
str.match(/(.*?)\s/)[1]
0 means the whole matched string, and 1 means the first group, which is exactly what you want.
@codaddict give another solution.
str.match(/(.*?)(?=\s)/)[0]
(?=\s) means lookahead but not consume whitespace, so the whole matched string is '14:00:00' but without whitespace.
You can use positive lookahead assertions as:
(.*?)(?=\s)
which says match everything which is before a whitespace but don't match the whitespace itself.
Yes there is, you can use character classes:
var str = '14:00:00 GMT';
str.match(/[^\s]*/)[0]; //matches everything except whitespace
Your code is quite close to the answer, you just need to replace [0] with [1]. When str.match(/:(.*?):/) is executed, it returns an object, in this example, the object length is 2, it looks like this:
[":00:","00"]
In index 0, it stores the whole string that matches your expression, in index 1 and later, it stores the result that matches the expression in each brackets.
Let's see another example:
var str = ":123abcABC:";
var result = str.match(/:(\d{3})([a-z]{3})([A-Z]{3}):/);
console.log(result[0]);
console.log(result[1]);
console.log(result[2]);
console.log(result[3]);
And the result:
:123abcABC:
123
abc
ABC
Hope it's helpful.
Try this,
.*(?=(\sGMT))
RegexBuddy ScreenShot