please, I have an array of unaccepted characters and I want if unknown word or sentence contains any of this characters. If now, I can add it to my words
array
I have the code:
// Define dictionary
let words = []
// Unaccepted characters
const unacceptedChars = [' ', '-', ',', '.']
let word = 'blue world'
if(!word.includes(unacceptedChars)) {
console.log('This sentence doesn\'t contain any of unaccepted chars and could be used')
} else {
console.log('Sentence can\'t be used')
}
The result is
This sentence doesn't contain any of unaccepted chars and could be used
which is wrong because word contains a space which is unaccepted character.
If I edit the code to
// Define dictionary
let words = []
// Unaccepted characters
const unacceptedChars = [' ']
let word = 'blue world'
if(!word.includes(unacceptedChars)) {
console.log('This sentence doesn\'t contain any of unaccepted chars and could be used')
} else {
console.log('Sentence can\'t be used')
}
all works OK. Result is Sentence can't be used
Please, how I look in array in Javascript? I tried find the answer but I didn't found yet. Thanks for any advice
CodePudding user response:
You can't use includes
with array as parameter
the properly way is
try {
unacceptedChars.forEach(char => {
if(word.includes(unacceptedChars)) {
Throw new Error('Sentence can\'t be used')
}
})
console.log('This sentence doesn\'t contain any of unaccepted chars and could be used')
} catch(error => {
console.error(error.message)
})
CodePudding user response:
Thanks for inspiration to all. My finally solution is
let words = []
const unacceptedChars = [' ', '-', '.', ',']
let newWord = $(this).text()
for (let i = 0; i < unacceptedChars.length; i ) {
if (newWord.includes(unacceptedChars[i])) {
allowedWord = false
break
}
}
if (allowedWord) words.push(newWord)
Thanks again to all