想請問各位大佬
有一個題目是
let word = ['靠','乾','它螞的']
若有一個函式是
function Word(word){
}
Word('靠,它螞的今天運氣超差,乾');
若參數的文字裡有包括陣列裡的字
輸出會變成 *** ,今天運氣超差,
大概會用什麼方式來處理
使用array.forEach + replace依序過濾 filterWords 陣列當中的文字
function Word(word){
const filterWords = ['靠','乾']
filterWords.forEach(filterWord => {
filterRegExp = new RegExp(filterWord, 'g')
word = word.replace(filterRegExp, '***')
})
return word
}
console.log(Word('靠,今天運氣超差,乾'));
https://jsfiddle.net/bwsmrndy/
使用array.reduce + replace 依序過濾 filterWords 陣列當中的文字
function Word(word){
const filterWords = ['靠','乾']
return filterWords.reduce((allWords, filterWord) => {
filterRegExp = new RegExp(filterWord, 'g')
return allWords.replace(filterRegExp, '***')
}, word)
}
console.log(Word('靠,今天運氣超差,乾'));
https://jsfiddle.net/Lskq35px/
使用for...of + replace 依序過濾 filterWords 陣列當中的文字
function Word(word){
const filterWords = ['靠','乾']
for (let filterWord of filterWords) {
filterRegExp = new RegExp(filterWord, 'g')
word = word.replace(filterRegExp, '***')
}
return word
}
console.log(Word('靠,今天運氣超差,乾'));
感謝大佬!!!
rogeryao: 改用 '靠靠,靠今天運氣超差,乾' 試試吧
幫補一個土法鍊鋼修正bug的範例:
<script>
function Word(word){
const filterWords = ['靠','乾']
filterWords.forEach(filterWord => {
word = word.replace(filterWord, '***')
})
return word
}
console.log(Word('靠乾靠靠今天靠運氣超差,乾'));
function Word2(word){
let finalword='';
const filterWords = ['靠','乾'];
for (i=0;i<word.length;i++){
finalword+=filterWords.includes(word[i])?"***":word[i];
}
return finalword;
}
console.log(Word2('靠乾靠靠今天靠運氣超差,乾'));
</script>
const blacklist = ['靠','乾','他嗎的']
const pat = new RegExp(blacklist.join("|"), "gm")
'靠,今天運氣超差,乾'.replaceAll(pat, "***")
result: ",今天運氣超差,"
補ie11作法,更早之前我就不想花時間了。
var blacklist = ['靠','乾','他嗎的']
var pat = new RegExp(blacklist.join("|"), "gm")
'靠,今天運氣超差,乾'.replace(pat, "***")