![](/img/trans.png)
[英]Is there a way to filter part of the string from an array of object with a given array of string
[英]Filter an array of string and replace a part of the string
我有一个包含字符串列表的数组(它很长,这只是一个例子),我想要做的是过滤所有以'INSERT ALL'开头的字符串并通过字符串修改括号内的数字' 无效的'
这是原始数组:
let arrSt = [ 'INSERT ALL bmw model 320d (111, bmw)', 'ford focus st d (222, ford)', 'INSERT ALL audi a5 rs (333, audi)', 'opel astra d (444, opel)', ]
这是我要获取的数组:
[ 'INSERT ALL bmw model 320d (NULL, bmw)', 'ford focus st d (222, ford)', 'INSERT ALL audi a5 rs (NULL, audi)', 'opel astra d (444, opel)', ]
这就是我所做的:
arrSt.filter((items: any) => items.startsWith('INSERT ALL')).map((item: any) => item.replace(/\(\d+,/g, '(NULL,'))
在控制台显示结果的时候, console.log(arrSt)
返回的是原来的数组,没有任何修改,我用了很短时间的.map,为什么不影响数组呢?
更新:
从字符串数组中识别以该字符串开头的元素。 也就是说:
这是数组: ['bmw', 'ferrari']
我需要修改所有以 INSERT ALL bmw 和 INSERT ALL ferrari 开头的元素。
在这种情况下,只有第一条记录会被更新,因为第二条记录以 INSERT ALL audi 开头
要保留所有项目,包括那些不会改变的项目,您可能不需要使用Array#filter
但Array#map
和if
如下:
const arrSt = [ 'INSERT ALL bmw model 320d (111, bmw)', 'ford focus st d (222, ford)', 'INSERT ALL audi a5 rs (333, audi)', 'opel astra d (444, opel)' ], newArr = arrSt.map( item => item.startsWith('INSERT ALL')? //check if the item starts with 'INSERT ALL' item.replace(/\(\d+,/g, '(NULL,'): //change it if it does item //leave it unchanged if it does not ); console.log( newArr );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.