147

hello I am trying what I thought would be a rather easy regex in Javascript but is giving me lots of trouble. I want the ability to split a date via javascript splitting either by a '-','.','/' and ' '.

var date = "02-25-2010";
var myregexp2 = new RegExp("-."); 
dateArray = date.split(myregexp2);

What is the correct regex for this any and all help would be great.

Craig
  • 3,043
  • 8
  • 24
  • 25

7 Answers7

222

You need the put the characters you wish to split on in a character class, which tells the regular expression engine "any of these characters is a match". For your purposes, this would look like:

date.split(/[.,\/ -]/)

Although dashes have special meaning in character classes as a range specifier (ie [a-z] means the same as [abcdefghijklmnopqrstuvwxyz]), if you put it as the last thing in the class it is taken to mean a literal dash and does not need to be escaped.

To explain why your pattern didn't work, /-./ tells the regular expression engine to match a literal dash character followed by any character (dots are wildcard characters in regular expressions). With "02-25-2010", it would split each time "-2" is encountered, because the dash matches and the dot matches "2".

Daniel Vandersluis
  • 91,582
  • 23
  • 169
  • 153
  • 5
    You could also mention that a dot *doesn't* have any special meaning inside of a character class - instead of acting as a wildcard character (which wouldn't make any sense), it acts as a literal. – Bobby Jack Jul 17 '14 at 10:20
14

or just (anything but numbers):

date.split(/\D/);
Jo3y
  • 159
  • 1
  • 3
6

Say your string is:

let str = `word1
word2;word3,word4,word5;word7
word8,word9;word10`;

You want to split the string by the following delimiters:

  • Colon
  • Semicolon
  • New line

You could split the string like this:

let rawElements = str.split(new RegExp('[,;\n]', 'g'));

Finally, you may need to trim the elements in the array:

let elements = rawElements.map(element => element.trim());
Bobzius
  • 188
  • 2
  • 4
6

you could just use

date.split(/-/);

or

date.split('-');
Brandon
  • 68,708
  • 30
  • 194
  • 223
Allan Ruin
  • 5,229
  • 7
  • 37
  • 42
5

Then split it on anything but numbers:

date.split(/[^0-9]/);
slm
  • 15,396
  • 12
  • 109
  • 124
useless
  • 1,876
  • 17
  • 18
0

or just use for date strings 2015-05-20 or 2015.05.20

date.split(/\.|-/);
Piotr
  • 377
  • 4
  • 11
-2

try this instead

date.split(/\W+/)

Omar
  • 9