简体   繁体   English

Javascript:如何删除数组中字符串内的特定字符值

[英]Javascript: How to delete specific character values within strings within an array

I am trying to remove punctuation from each string within an array, but this problem would exist for trying to delete any type of character within strings within an array. 我正在尝试从数组中的每个字符串中删除标点符号,但是尝试删除数组中的字符串中的任何类型的字符都会存在此问题。

I have attempted to create 3 loops: The first loop iterates over each item in arrayA that I'm aiming to edit. 我尝试创建3个循环:第一个循环遍历我要编辑的arrayA中的每个项目。 The second loop iterates through each character in each string in arrayA. 第二个循环遍历arrayA中每个字符串中的每个字符。 The third loop checks whether the character in arrayA matches any character in arrayB, and deletes it if it does. 第三个循环检查arrayA中的字符是否与arrayB中的任何字符匹配,如果匹配,则将其删除。

Nothing is being deleted however, and I'm not sure why. 但是,什么都没有被删除,我不确定为什么。

This is my code so far: 到目前为止,这是我的代码:

let arrayA = ['abc', 'def', 'ghi'];
let arrayB = ['a', 'e', 'i', 'o', 'u'];

arrayA.forEach((item) => {
    for (let i=0; i < item.length; i++) {
        for (let arrayBIndex = 0; arrayBIndex < arrayB.length; arrayBIndex++) {
            item.replace(arrayB[arrayBIndex], '');
        };
    };
});
console.log(arrayA);

I have searched for other questions dealing with this, but I haven't been able to find any answers, specifically where the elements to delete are contained in another list. 我已经搜索了与此相关的其他问题,但是却找不到任何答案,特别是要删除的元素包含在另一个列表中的位置。 Thank you for your help. 谢谢您的帮助。

You can generate regular expression using arrayB and then using array#map iterate through each word in arrayA and use string#replace to get rid of words from arrayB . 您可以使用arrayB生成正则表达式,然后使用array#map遍历arrayA每个单词,并使用string#replace摆脱arrayB的单词。

 let arrayA = ['abc', 'def', 'ghi'], arrayB = ['a', 'e', 'i', 'o', 'u'], regExp = new RegExp(arrayB.join('|'), 'g'), result = arrayA.map(word => word.replace(regExp, '')); console.log(result); 

If you wish to follow with arrays, I would suggest to transform your strings into an array of characters and using array filter operator. 如果您希望使用数组,建议您将字符串转换为字符数组,并使用数组过滤器运算符。

However you can probably achieve what you want to do with regular expressions 但是,您可以使用正则表达式实现您想做的事情

  const arrayA = ['abc', 'def', 'ghi']; const arrayB = ['a', 'e', 'i', 'o', 'u']; const result = arrayA .map(s => [...s]) // array of chars .map(chars => chars.filter(ch=>!arrayB.includes(ch)).join(''))//filter out invalid char and transform back into string console.log(result) 

 const result = arrayA.map(item => {
   let replaced = "";
   for(const char of item)
     if(!arrayB.includes(char)) 
        replaced += char;
   return replaced;
});

Strings are immutable. 字符串是不可变的。 Every mutation returns a new string instead of mutating the original. 每个突变都会返回一个新字符串,而不是对原始字符串进行突变。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM