Pepe
Pepe

Reputation: 1002

jQuery "split" options?

I use jQuery to sort some dates.

Thats the html div:

<div class="the_date">30/11/2015, 19:24</div>

Thats the part of jQuery:

var date1 = $(a).find(".the_date").text();
  date1 = date1.split('/');
  date1 = new Date(date1[2], date1[1] - 1, date1[0], date1[3], date1[4]);

My problem: it will only works if the date looks like this (because of the split option):

<div class="the_date">30/11/2015/19/24</div>

Is there a way to split in different ways? For example first "/", if not exist "," if not exist ":"? Or is that a bad way?

Upvotes: 0

Views: 198

Answers (3)

spozun
spozun

Reputation: 882

date1 = date1.split(/\/|,|:/g);

Upvotes: 1

epascarello
epascarello

Reputation: 207557

Do not worry about matching all of the different separators. Just match the numbers with the regular expression \d+:

"30/11/2015, 19:24".match(/\d+/g).map(Number);

Note: The .map(Number) is not needed, it is just a neat way to convert the array of strings to numbers.

Result with: [30, 11, 2015, 19, 24]
Result without: ["30", "11", "2015", "19", "24"]

Upvotes: 3

nderscore
nderscore

Reputation: 4261

The split method accepts regular expressions as an argument to split by.

Here's some examples:

var str = '30/11/2015, 19:24';
var parts = str.split(/[\/,: ]+/); // split by a specific set of characters
console.log(parts);
// ["30", "11", "2015", "19", "24"]
var str = '30/11/2015, 19:24';
var parts = str.split(/\D+/); // split by all non-digit characters
console.log(parts);
// ["30", "11", "2015", "19", "24"]

Upvotes: -1

Related Questions