簡體   English   中英

從字符串中刪除字符的更簡單方法javascript

[英]Simpler way to remove characters from a string javascript

我有一系列評論,我希望生成一個字符串,刪除除az'之外的所有字符

編輯::我實際上希望刪除除az'之外的所有字符,在單詞之間只保留一個空格,並將所有大寫字母小寫

這是我當前的代碼,它有效,

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(/it\ss\s/g, "it's ")
replaceNum  = replaceApos.replace(/[0-9]/g, "")
replaceWhi  = replaceNum.replace(/\s\s+/g, " ")

但是有人可以提出更好/更有效/更簡單的修復方法嗎?

如果 regexp 需要不同的輸出,可以將它們鏈接成一個嗎?

謝謝

 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('');

這允許以一種超級可讀的方式來配置允許使用的字母

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM