Reputation: 15925
If I have a string which contains
abc: def - 01:00, ghi - 02:00
Any part of this string can change, except the order of the dividers in the string i.e. :
, -
, :
, ,
, -
, and :
How do I get the text before the first :
and stick it into a variable for later use?
And also, how do I get the text between the first -
and ,
and stick that into a different variable?
Upvotes: 0
Views: 247
Reputation: 359786
How do I get the text before the first
:
and stick it into a variable for later use?
var text = 'abc: def - 01:00, ghi - 02:00',
firstChunk = text.substring(0, text.indexOf(':'));
// firstChunk is "abc"
And also, how do I get the text between the first
-
and,
and stick that into a different variable?
var secondChunk = text.substring(text.indexOf('-') + 1, text.indexOf(','));
// secondChunk is " 01:00"
String.indexOf
String.substring
" 01:00"
) use String.trim
Upvotes: 6
Reputation:
You can match the string with Javascript's Regexp engine. For example:
var expression = /expression_to_match/;
expression.match(your_string);
Now you can access the matched elements with RegExp.$1
etc.
A suitable regular expression for your string would be:
/(\w+): (\w+) - (\d\d:\d\d), (\w+) - (\d\d:\d\d)/
Upvotes: 1