首页 > 解决方案 > 从字符串函数数组中删除标点符号

问题描述

我目前正在用 JavaScript 做一个项目,该项目涉及我从字符串数组中删除某些标点符号(如数组“greetings”)。我使用迭代器循环遍历数组中的每个项目,然后我编写了一个循环来遍历当前项目中的每个字母。我声明了一个空变量,用于根据字母是否不是双引号、句点或感叹号来连接每个字母。然后在遍历完单词中的所有字母后,我将最终连接的字符串返回到映射迭代器中。当我尝试打印 noPunctGreetings 时,我得到了空字符串。

const greetings = ['Hi,', 'my', 'name', 'is', 'Dave!']

const noPunctGreetings = greetings.map(word => {
  let concatedWord = '';
  for (let i = 0; i < word.length; i++) {
    if (word[i] != '"' || word[i] != '.' || word[i] != '!') {
      concatedWord.concat(word[i].toLowerCase());
    } 
  }
  return concatedWord;
})

console.log(noPunctGreetings)

>>> ['', '', '', '', '']

如果有另一种更清洁的方法可以做到这一点,请告诉我。

标签: javascriptarraysiterator

解决方案


https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/concat

concat() 方法将字符串参数连接到调用字符串并返回一个新字符串。

所以你需要做

concatedWord = concatedWord.concat(word[i].toLowerCase());

此外,您需要执行以下操作:

word[i] != '"' && word[i] != '.' && word[i] != '!'

而不是||, 因为word[i]总是不是"或不是.

const greetings = ['Hi,', 'my', 'name', 'is', 'Dave!']

const noPunctGreetings = greetings.map(word => {
  let concatedWord = '';
  for (let i = 0; i < word.length; i++) {
    if (word[i] != '"' && word[i] != '.' && word[i] != '!') {
      concatedWord = concatedWord.concat(word[i].toLowerCase());
    } 
  }
  return concatedWord;
})

console.log(noPunctGreetings)

或者,更简单地说:

const greetings = ['Hi,', 'my', 'name', 'is', 'Dave!']

const noPunctGreetings = greetings.map(word => word.replace(/[."!]/g, "").toLowerCase())

console.log(noPunctGreetings)


推荐阅读