Question about Javascript split regex

Hi, I am trying to do what I thought would be a fairly simple regular expression in Javascript, but it causes a lot of problems. I want the ability to split the date using javascript separating either '-', '.', '/' AND ''.

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

What is the right regex for this to help any help.

+83
javascript split regex
Aug 24 '10 at 18:44
source share
6 answers

You need to put the characters you want to split into a character class that tells the regex engine "any of these characters match." For your purposes, it will look like this:

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

Although dashes have special meaning in character classes as a range specifier (that is, [az] means the same as [abcdefghijklmnopqrstuvwxyz] ), if you put it as the last in the class, it means that it is a literal dash and does not need to run.

To explain why your pattern doesn't work, /-./ tells the /-./ engine to match an alphanumeric character dash followed by any character ( dots are wildcards in regexes). From "02-25-2010" it will be broken every time "-2" is encountered, because the dash matches, and the point corresponds to "2".

+128
Aug 24 '10 at 19:02
source share

or simply (nothing but numbers):

 date.split(/\D/); 
+7
Nov 12 '13 at 20:07
source share

you can just use

 date.split(/-/); 

or

 date.split('-'); 
+6
Jan 23 '12 at 17:02
source share

Then divide it into anything but numbers:

 date.split(/[^0-9]/); 
+4
Aug 20 '13 at 20:25
source share

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

 date.split(/\.|-/); 
0
May 20 '15 at
source share

Say your line is:

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

You want to split the string into the following delimiters:

  • Colon
  • Semicolon
  • New line

You can split the string as follows:

 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()); 
0
Jan 21 '19 at 17:33
source share



All Articles