oshirowanen
oshirowanen

Reputation: 15925

Working with strings

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

Answers (3)

Matt Ball
Matt Ball

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 function reference:

Upvotes: 6

user794316
user794316

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

dotty
dotty

Reputation: 41433

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.

Upvotes: 0

Related Questions