Working with strings
If I have a string which con开发者_开发技巧tains
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?
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 function reference:
String.indexOf
String.substring
- To get rid of excess whitespace (as in
" 01:00"
) useString.trim
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)/
Javascripts' split method.
string.split(what we're splitting with)
(returned as an array)
So in your example we could use string.split(":")[0]
to get the first part of the string.
精彩评论