Reputation: 2982
I have a string that I want to parse using javascript. The string contents are
Tue Apr 02 2013 13:36:56 GMT -0500 (Central Daylight Time)
I need to get javascript to "get the word after open parenthesis" (in this case "Central").
I can't seem to figure out the javascript code for that. Any suggestions are appreciated.
Upvotes: 0
Views: 82
Reputation: 50905
Using a regex, you could use this:
var re = /\(([A-Za-z0-9]+)[ )]/;
var str = "Tue Apr 02 2013 13:36:56 GMT -0500 (Central Daylight Time)";
var matching = str.match(re);
DEMO: http://jsfiddle.net/BzxtY/
Since you want the specific word, you'd use matching[1]
to get the specific word matched. Of course, the match could be null
, so you might want to check that first. If you're sure this regex will match, don't bother :)
To break it down:
\(
- Starts with (
(
- (beginning of matching group)
[A-Za-z0-9]+
- Contains any at least one of A-Z, a-z, 0-9
)
- (end of matching group)
[ )]
- Ends with a (space) or
)
The final part should match a single word in the ()
or multiple words (and only get the first, as you want). Such as matching "Central" in "(Central Daylight Time)" or matching "Testing" in "(Testing)".
Upvotes: 4
Reputation: 2365
I agree - regex is the way (especially were it to be elegant):
<string>.replace(/.*\(([^\s]*)\s.*/,'$1');
(n.b. There will be more elegant regex for this)
Cheers.
Upvotes: 0
Reputation: 67207
Try this,
var xStr="Tue Apr 02 2013 13:36:56 GMT -0500 (Central Daylight Time)"
alert(xStr.substring(xStr.indexOf("(")+1).split(" ")[0]);
[Concepts used: substring, indexOf, split]
Upvotes: 2
Reputation: 940
Use indexOf() to get the index of the first paren. Once you have that then get all of the characters up to the next space.
var str = "Tue Apr 02 2013 13:36:56 GMT -0500 (Central Daylight Time)";
var parenIdx = str.indexOf('(') + 1;
var result = str.substring(parenIdx, str.indexOf(' ', parenIdx));
Upvotes: 1