Mattew Trincanati
Mattew Trincanati

Reputation: 191

Split the date! (It's a string actually)

I want to split this kind of String :

"14:30 - 19:30" or "14:30-19:30"

inside a javascript array like ["14:30", "19:30"]

so I have my variable

var stringa = "14:30 - 19:30";
var stringes = [];

Should i do it with regular expressions? I think I need an help

Upvotes: 4

Views: 95

Answers (6)

Paul S.
Paul S.

Reputation: 66304

Don't forget that you can pass a RegExp into str.split

'14:30 - 19:30'.split(/\s*-\s*/); // ["14:30", "19:30"]
'14:30-19:30'.split(/\s*-\s*/); // ["14:30", "19:30"]

Upvotes: 0

semyjr01
semyjr01

Reputation: 9

var stringa = '14:30 - 19:30';
var stringes = stringa.split("-");

Upvotes: 1

Deepak
Deepak

Reputation: 1545

Try this :

var stringa = "14:30 - 19:30";
var stringes = stringa.split("-");   // string is "14:30-19:30" this style

or

var stringes = stringa.split(" - "); // if string is "14:30 - 19:30"; style so it includes the spaces also around '-' character. 

The split function breaks the strings in sub-strings based on the location of the substring you enter inside it "-"

. the first one splits it based on location of "-" and second one includes the spaces also " - ".

*also it looks more like 24 hour clock time format than data as you mentioned in your question.

Upvotes: 1

wolffer-east
wolffer-east

Reputation: 1069

.split is probably the best way to go, though you will want to prep the string first. I would go with str.replace(/\s*-\s*/g, '-').split('-'). to demonstrate:

var str = "14:30 - 19:30"
var str2 = "14:30-19:30"
console.log(str.replace(/\s*-\s*/g, '-').split('-')) //outputs ["14:30", "19:30"]
console.log(str2 .replace(/\s*-\s*/g, '-').split('-')) //outputs ["14:30", "19:30"]

Upvotes: 0

ssube
ssube

Reputation: 48247

If you know that the only '-' present will be the delimiter, you can start by splitting on that:

let parts = input.split('-');

If you need to get rid of whitespace surrounding that, you should trim each part:

parts = parts.map(function (it) { return it.trim(); });

To validate those parts, you can use a regex:

parts = parts.filter(function (it) { return /^\d\d:\d\d$/.test(it); });

Combined:

var input = "14:30 - 19:30";
var parts = input.split('-').map(function(it) {
  return it.trim();
}).filter(function(it) {
  return /^\d\d:\d\d$/.test(it);
});

document.getElementById('results').textContent = JSON.stringify(parts);
<pre id="results"></pre>

Upvotes: 2

Kasravnd
Kasravnd

Reputation: 107287

You can just use str.split :

var stringa = "14:30 - 19:30";
var res = str.split("-");

Upvotes: 2

Related Questions