javascript - 从字符串函数数组中删除标点符号
问题描述
我目前正在用 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)
>>> ['', '', '', '', '']
如果有另一种更清洁的方法可以做到这一点,请告诉我。
解决方案
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)
推荐阅读
- objective-c - 如何在 MacOS 中保持沙盒模式获得批准的同时获取用户的 IP 地址?
- angular - 在包装器中显示 Angular Material mat-error
- c# - .NET Azure 函数 - 如何从流中返回 JSON 对象?
- c++ - Visual Studio 2015:外部“C”和“export”关键字
- python - 如何在预测中返回多个项目?
- excel - Excel 2016 Power Query 无法加载到电子表格
- scala - 可以将 udf 包装器添加到此数据帧操作
- ruby-on-rails - Spree API 身份验证扩展不起作用
- hive - 如何在 NiFi 中使用 UDF?
- tfs - 哪个是迭代 ID?