>我在 Angular 中有一个响应式表单,它将文件格式作为文本输入获取
<input type="text" name="formats" formControlName= "formats">
例如:.txt, .zip, .tar.gz
我需要将这些输入转换为数组列表。在@danday74的帮助下,我可以做到这一点。这是代码:
const input = ".txt, .zip, .tar.gz"
const parts = input.split(' ')
const output = parts.map(x => x.replace(',', '').replace('.', ''))
console.log(output)
代码生成的输出是 ["txt","zip","tar.gz"]
,这是我所期望的。
但是,我担心的是,如果用户输入类似.. ., .tar.gf.ds ,.tar
或tar tar.gz zip
输出将分别[".","","tar.gf.ds","tar"]
和["tar","targz","zip"]
我的问题是我如何以这样一种方式实现这一点,即用户可以在没有任何特定结构的情况下输入文件格式(例如:.txt, .zip, .tar.gz,
.txt .zip .tar.gz
、txt, zip, tar.gz
、txt zip tar.gz
(,并且我应该能够生成这样的输出["txt","zip","tar.gz"]
。 就像如果输入只是..
或.,
,我应该能够忽略输入,只考虑带有字符串的输入。
如果您只关心领导.
和,
,则可以按如下方式使用正则表达式:
const input = '.txt, .zip, .tar.gz, ,.tar, txt, zip, tar.gz, .., .,'
const output = input.split(', ')
.map(ext => ext.replace(/^W+/, '')) // remove any character that's not a word character from the beginning of each string
.filter(Boolean); // filter just to remove empty strings
console.log(output);
如果您还需要删除尾随字符,则可以修改正则表达式以从末尾删除它们:
const input = '.txt, .zip, .tar.gz, ,.tar, txt, zip, tar.gz, .txt., .tar.gz., ,.tar,., .., .,'
const output = input.split(' ') // split on space character as trailing commas will be handled in the regex
.map(ext => ext.replace(/^W+|W+$/g, ''))
.filter(Boolean);
console.log(output);
如果还有其他考虑因素,请告诉我。
这是您如何做到这一点的一般方法!
如果字符串中的任何位置有两个..
!不要添加它。
可能留下了一些用例,如果有的话,请发表评论
var strings = [
".txt, .zip, .tar.gz",
"..txt .zip .tar.gz a.b.should.be.in",
"txt, zip, tar.gz",
".., ..., ...., .this.should.be.in, .not..this"
]
var extensions = []
strings
.forEach((item) => {
let items = item.split(',');
if (items.length <= 1) {
items = item.split(' ');
}
items.forEach(ext => {
const trimedExt = ext.trim()
if (
trimedExt.indexOf('..') === -1
) {
if (trimedExt[0] === '.') {
extensions.push(trimedExt.substr(1))
} else {
extensions.push(trimedExt)
}
}
});
})
console.log(extensions)