去掉 。和,在Angular 6中数组列表中每个元素的开头/结尾 [英] Remove . and , in the beginning/end of every element from the array list in Angular 6

查看:74
本文介绍了去掉 。和,在Angular 6中数组列表中每个元素的开头/结尾的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Angular中有一个反应形式,它以文件格式作为文本输入

I have a reactive form in Angular which gets file format as text input

<input type="text" name="formats" formControlName= "formats">

例如: .txt,.zip,.tar.gz

我需要将这些输入转换为数组列表。在@ danday74的帮助下,我能够做到这一点。这是代码:

I needed to convert those inputs as an array list. With the help of @danday74, I can able to do that. here is the code:

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] ,这是我期望的。

The output generated by the code is ["txt","zip","tar.gz"], which is what I expected.

但是,我担心的是,如果用户输入这样的内容 .. .. .tar.gf.ds,.tar tar tar.gz zip ,输出为 [。,, tar.gf.ds, tar] [ tar, targz, zip]

However, my concern is, if a user enters something like this .. ., .tar.gf.ds ,.tar or tar tar.gz zip the output will be [".","","tar.gf.ds","tar"] and ["tar","targz","zip"] respectively

我的问题是我该如何实现这种方式,使用户可以输入没有任何特定结构的文件格式(例如: .txt,.zip,.tar.gz, .txt .zip .tar.gz txt,zip,tar.gz txt zip tar.gz ),我应该能够生成这样的输出: [ txt, zip, tar.gz] 。就像我应该能够忽略输入只是 .. 。,的输入,而只考虑输入

My question is how do I implement this in such a way that a user can enter the file format without any specific structure (for Eg: .txt, .zip, .tar.gz, .txt .zip .tar.gz, txt, zip, tar.gz, txt zip tar.gz ) and I should be able to generate the output like this ["txt","zip","tar.gz"]. like I should be able to neglect the input if it is just .. or ., and only consider the input with string.

推荐答案

如果您只担心以开头。,您可以按如下方式使用正则表达式:

If you're only concerned about leading . and ,, you could use a regex as follows:

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);

如果您还需要删除结尾字符,则可以修改正则表达式以将其从结尾处也删除:

If you also need to remove trailing characters you could modify the regex to remove them from the end as well:

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);

让我知道是否还有其他注意事项。

Let me know if there are any other considerations.

这篇关于去掉 。和,在Angular 6中数组列表中每个元素的开头/结尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆