繁体   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