How to split strings of format like "12-12-1990" or "12/12/1990" where - and / are the delimiters. I have seen answers using regex but I am not proficient in it. Answers regarding this will be helpful as I am a beginner
Asked
Active
Viewed 4,694 times
0
-
2Does this answer your question? [How do I split a string with multiple separators in javascript?](https://stackoverflow.com/questions/650022/how-do-i-split-a-string-with-multiple-separators-in-javascript) – Ravi Makwana Jan 31 '20 at 06:03
-
I am unable to understand answers there – Nirmal Kumar Jan 31 '20 at 10:03
3 Answers
2
You can pass a regex into Javascript's split operator. For example:
"12-12-1990".split(/-|\//)
["12", "12", "1990"]
"12/12/1990".split(/-|\//)
["12", "12", "1990"]

Ravi Makwana
- 2,782
- 1
- 29
- 41
2
try this
"2020-01-31".split(/[/-]/ig)
var dateParts1 = "2020-01-31".split(/[/-]/ig);
console.log(dateParts1);
var dateParts2 = "2020/02/21".split(/[/-]/ig);
console.log(dateParts2);

Abdelrahman Gobarah
- 1,544
- 2
- 12
- 29
-
Why `i` modifier? Are you expecting these chars to be uppercased? – customcommander Jan 31 '20 at 06:07
-
1not important but he said that he is not an expert in regex, so I put it if he need to add more chars or other example – Abdelrahman Gobarah Jan 31 '20 at 06:08
-
-
the above expression do this in single one, see the explain of regex – Abdelrahman Gobarah Jan 31 '20 at 06:30
-
1
-
**i flag**: With this flag the search is case-insensitive: no difference between A and a – Abdelrahman Gobarah Jan 31 '20 at 10:07
-
**g flag**: With this flag the search looks for all matches, without it – only the first match is returned. – Abdelrahman Gobarah Jan 31 '20 at 10:07
-
for more see https://javascript.info/regexp-introduction#flags – Abdelrahman Gobarah Jan 31 '20 at 10:07
-1
You can use split with the delimiter on which you want to split the string
var x="12-12-1990";
console.log(x.split('-'))

ellipsis
- 12,049
- 2
- 17
- 33