gpt4 book ai didi

javascript - 消除 。并且,在 Angular 6 中数组列表中每个元素的开头/结尾

转载 作者:搜寻专家 更新时间:2023-11-01 04:12:40 24 4
gpt4 key购买 nike

我在 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 ,.tartar 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);

如果还有其他注意事项,请告诉我。

关于javascript - 消除 。并且,在 Angular 6 中数组列表中每个元素的开头/结尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51758176/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com