Using .split () to convert a string to an array (improvement required)

I am trying to use JavaScript to convert 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 holds a dot in front of the first element. What can I do since I don't know the regex? Here is my code:

let fileTypes = string.split('|.');
+4
source share
5 answers

Something like that:

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

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

First you divide all the points, then divide by |. Pipe separation is all that matters ... So it will take a more flexible line if that matters.

+3
source

The problem only seems to be the first point, so you can just do

s = ".txt|.pdf|.xls|.xlsx|.doc|.docx|.rtf|.jpg|.jpeg|.png|.gif"
s.substr(1).split("|.")
+6
source

split(). :

let fileTypes = string.replace(/^\./,'').split('|.');

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

var fileTypes = string.replace(/^\./,'').split('|.');

console.log(fileTypes);
Hide result
+1

.split .join :

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

var newstring =  typeFile.split('.').join('').split('|');
console.log(newstring);
Hide result
0

The substr () method extracts parts of a string, starting at the character at the specified position, and returns the specified number of characters. Therefore, it would be better if you first used substr from the first position, and then either used split (), as you did.

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

0
source

Source: https://habr.com/ru/post/1629638/


All Articles