从字符串 JavaScript 中删除字符的更简单方法



我有一系列评论,我想生成一个字符串,删除除a-z'以外的所有字符

编辑::我实际上希望删除除a-z'以外的所有字符,在单词之间只保留一个空格,并小写任何大写字母

这是我当前的代码,它有效,

let words = ["A great product for daily use",
"Great price. Takes about 10days for delivery",
"Excellent value - will buy again",
"Fine, I always use this, was as expected",
"Good value",
"excellent product, good value",
"good",
"does the job!",
"Thank you",
"Great it's that is easy to use",
"I hated it",
"arrived on time, excellent product, thank you",
"quick service great price.",
"good and refreshing",
"My daughter is road testing this, but so far it's refreshing",
"DO NOT BUY THIS PRODUCT",
"Avoid",
"Did not notice any difference",
"Horrible taste",
"Does its job and shows it works"]
joinedwords = words.join(' ')
removeChars = joinedwords.replace(/[^w]/gi, " ").toLowerCase()
replaceApos = removeChars.replace(/itsss/g, "it's ")
replaceNum  = replaceApos.replace(/[0-9]/g, "")
replaceWhi  = replaceNum.replace(/ss+/g, " ")

但是有人可以提出更好/更有效/更简单的解决方法吗?

如果正则表达式需要不同的输出,它们可以链接成一个吗?

谢谢

let words = ["A great product for daily use",
"Great price. Takes about 10days for delivery",
"Excellent value - will buy again",
"Fine, I always use this, was as expected",
"Good value",
"excellent product, good value",
"good",
"does the job!",
"Thank you",
"Great it's that is easy to use",
"I hated it",
"arrived on time, excellent product, thank you",
"quick service great price.",
"good and refreshing",
"My daughter is road testing this, but so far it's refreshing",
"DO NOT BUY THIS PRODUCT",
"Avoid",
"Did not notice any difference",
"Horrible taste",
"Does its job and shows it works"];
joinedwords = words.join(' ');
removeChars = joinedwords.replace(/[^A-Za-z' ]/g, "").toLowerCase();
//Prints result
document.write(removeChars);

塔达。我运行了你的代码,运行了我的代码,它们似乎共享两个相同的结果,所以我猜这就是你想要的?顺便说一句,这是正则表达式的工作方式,它匹配任何不是字母、空格或撇号的字符。

joinedwords = words.join(' ')
removeChars = joinedwords.replace(/[^A-Za-z' ]/g, "").toLowerCase()

如果您希望在没有正则表达式的情况下执行此操作,一种可能的方法是使用如下数组过滤:

const allowedChars = 'abcdefghijklmnopqrstuvwxyz''.split('');
let arr = words.join(' ').toLowerCase().split('');
let finalStr = arr.filter(letter => allowedChars.includes(letter)).join('');

这允许以超级可读的方式配置允许的字母

最新更新