【问题标题】:Removing punctuation from an array of strings fuction从字符串函数数组中删除标点符号
【发布时间】:2021-09-13 21:32:11
【问题描述】:

我目前正在使用 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)

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

如果有其他更简洁的方法可以做到这一点,请告诉我。

【问题讨论】:

    标签: javascript arrays iterator


    【解决方案1】:

    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)

    【讨论】:

    • 非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-08
    • 1970-01-01
    • 2014-12-06
    相关资源
    最近更新 更多