Javascript split regex question

后端 未结 7 2050
小鲜肉
小鲜肉 2020-11-29 21:11

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 ei

7条回答
  •  再見小時候
    2020-11-29 21:44

    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".

提交回复
热议问题