Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using .split() to transform string to array (Improvement needed)

I'm trying to use JavaScript to transform this string

.txt|.pdf|.xls|.xlsx|.doc|.docx|.rtf|.jpg|.jpeg|.png|.gif

into this array

["txt", "pdf", "xls", "xlsx", "doc", "docx", "rtf", "jpg", "jpeg", "png", "gif"]

But it gives me this

[".txt", "pdf", "xls", "xlsx", "doc", "docx", "rtf", "jpg", "jpeg", "png", "gif"]

It keeps the dot in front of first element. What can I do since I don't know regex? Here is my code:

let fileTypes = string.split('|.');
like image 744
Gab Avatar asked Dec 25 '22 09:12

Gab


2 Answers

The problem only seems to be the first dot, so you could just do

s = ".txt|.pdf|.xls|.xlsx|.doc|.docx|.rtf|.jpg|.jpeg|.png|.gif"
s.substr(1).split("|.")
like image 178
bigblind Avatar answered Jan 17 '23 17:01

bigblind


Something like this:

var string = '.txt|.pdf|.xls|.xlsx|.doc|.docx|.rtf|.jpg|.jpeg|.png|.gif';

var arr = string.replace(/\./g,'').split('|');

This will first strip all of the dots, then split on the |. Separating by the pipe is all that matters... So it will take a more flexible string if that matters.

like image 27
Vinny M Avatar answered Jan 17 '23 17:01

Vinny M