簡體   English   中英

使用.split()將字符串轉換為數組(需要改進)

[英]Using .split() to transform string to array (Improvement needed)

我正在嘗試使用JavaScript來轉換此字符串

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

進入這個數組

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

但它給了我這個

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

它將點保持在第一個元素的前面。 因為我不知道正則表達式,我能做什么? 這是我的代碼:

let fileTypes = string.split('|.');

問題似乎只是第一個點,所以你可以這樣做

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

像這樣的東西:

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

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

這將首先剝離所有的點,然后拆分| 通過管道分離是最重要的......因此,如果重要的話,它將采用更靈活的字符串。

第一個點與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); 

我使用函數.split和.join如下:

 var typeFile = ".txt|.pdf|.xls|.xlsx|.doc|.docx|.rtf|.jpg|.jpeg|.png|.gif"; var newstring = typeFile.split('.').join('').split('|'); console.log(newstring); 

substr()方法從指定位置的字符開始提取字符串的一部分,並返回指定數量的字符。因此,如果您首先使用第一個位置的substr然后使用split()as,則會更好你做完了

s =“。txt | .pdf | .xls | .xlsx | .doc | .docx | .rtf | .jpg | .jpeg | .png | .gif”

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM