Uffo
Uffo

Reputation: 10046

JS Extract data from string

So I have the following string:

_string = 'From 00:00 To 01:23';

And I need to get the times in a format that I can work with, in order to save the data.

So I was thinking if I can get something like _string['from'] and _string['to'] and this way I can get the values and save them in the database.

So far I have tried .replace but I guess I don't have enough experience in JS in order to achieve what I'm looking for.

So this is what I have tried, I can get the To value, but didn't had any luck with from:

_string = 'From 00: 00 To 01:23';

res = _string.replace('From ','');
res2 = res.replace('To ','');

_one = _string.split('From ');
_two = _string.split('To');
console.log(_two[1]); //OUTPUS " 01:23"

Expected values: 00:00 for the From value and 01:23 for the TO value.

Upvotes: 2

Views: 3101

Answers (2)

guest271314
guest271314

Reputation: 1

You can use .replace() with RegExp /\s+/g to replace all space characters with empty string, .match() with RegExp /\d+:\d+/g to match one or more digits followed by colon character followed by one or more digits

var _string = 'From 00: 00 To 01:23';
var [from, to] = _string.replace(/\s+/g, "").match(/\d+:\d+/g);

console.log(from, to);

Upvotes: 2

Danny Bullis
Danny Bullis

Reputation: 3199

Try splitting on the empty space character.

var _string = "From 00:00 To 01:23";
var res = _string.split(' ');

// res == ['From', '00:00', 'To', '01:23'];

var outputFrom = res[1]; // 00:00
var outputTo = res[3]; // 01:23

console.log(outputFrom, outputTo);

Upvotes: 2

Related Questions